模板模式
一般在父类中定义抽象方法,然后组合该抽象方法的调用。子类自由实现该抽象方法。下面的例子中lifecycle表示了人的一生的历程模板:出生->工作->死亡。不同职业各有各的死法,比方说程序员的死法就是:扶我起来,我还能解决bug....
public static void main(String[] args) {
Person person = new Programmer("kaka", 22);
person.lifecycle();
}
@Data
@AllArgsConstructor
public static abstract class Person {
private String name;
private Integer age;
public void lifecycle() {
System.out.println(String.format("My name is:%s, old:%d", this.getName(), this.getAge()));
this.birth();
System.out.println("Hard work 30 years");
this.die();
}
protected abstract void birth();
protected abstract void die();
}
@Data
public static class Programmer extends Person {
public Programmer(String name, Integer age) {
super(name, age);
}
@Override
protected void birth() {
System.out.println("When i was born, i want to be a programmer");
}
@Override
protected void die() {
System.out.println("Help me up, i can solve bugs continue...");
}
}