What is the name of that pattern in java? Please see the implementation of RedirectAdultUserHandler1
and RedirectAdultUserHandler2
classes.
public class Main {
public static void main(String[] args) throws Exception {
new Main().run();
}
private void run() {
final List<User> users = Arrays.asList(
new User("john", 1),
new User("jeff", 22),
new User("jack", 333)
);
UserHandler handler1 = new RedirectAdultUserHandler1(new UserHandler());
UserHandler handler2 = new RedirectAdultUserHandler2();
handler1.processAll(users);
handler2.processAll(users);
}
}
class User {
private final String name;
private final int age;
User(final String name, final int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
class UserHandler {
public void processAll(List<User> users) {
users.forEach(user -> process(user, "users"));
System.out.println();
}
public void process(User user, String tableName) {
System.out.printf("%s stored into %s%n", user, tableName);
}
}
class RedirectAdultUserHandler1 extends UserHandler {
private final UserHandler original;
public RedirectAdultUserHandler1(final UserHandler original) {
this.original = original;
}
@Override
public void processAll(final List<User> users) {
original.processAll(users);
}
@Override
public void process(final User user, final String tableName) {
if (user.getAge() >= 18) {
original.process(user, "adult_users");
}
original.process(user, tableName);
}
}
class RedirectAdultUserHandler2 extends UserHandler {
@Override
public void process(final User user, final String tableName) {
if (user.getAge() >= 18) {
super.process(user, "adult_users");
}
super.process(user, tableName);
}
}
The RedirectAdultUserHandler1
is a decorator, but what about the RedirectAdultUserHandler2
one? Is there some name for that?
Aucun commentaire:
Enregistrer un commentaire