I have next classes:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Admin {
private String name;
private int age;
}
And I have some operations with template method pattern implimentation. Base Class with algorithm:
public abstract class Operation<T> {
public void process(T t){
System.out.println(t);
updateName(t);
System.out.println(t);
}
protected abstract void updateName(T t);
}
two childs with implementation template method:
@Component
public class UserOperation extends Operation<User> {
@Override
protected void updateName(User user) {
String newName = user.getName().toUpperCase();
user.setName(newName);
}
}
@Component
public class AdminOperation extends Operation<Admin> {
@Override
protected void updateName(Admin admin) {
String name = admin.getName();
StringBuilder builder = new StringBuilder();
builder.append(name);
StringBuilder reverse = builder.reverse();
admin.setName(reverse.toString());
}
}
My questions:
1) How do I rewrite this code to use the composition?
2) Do I understand correctly that when using the template method, I attach to inheritance?
The template method is a great way to avoid duplication. But if it binds me to inheritance, what other ways are there to avoid code duplication? in my example, how can I use composition? (replace the template method with something else?)
Aucun commentaire:
Enregistrer un commentaire