模板模式
模板方法:定义了框架,按某种顺序调用其包含的基本方法 把相同的部分抽象出来到抽象类中去定义,具体子类来实现具体的不同部分,这个思路也正式模板方法的实现精髓所在
/**
* @Author LWL
* @Date 2022/8/15 0:00
* @TODO 模板类
*/
public abstract class PersonDaily {
protected String name;
protected abstract TestModel method1();
protected abstract TestModel method2();
protected abstract TestModel method3();
// 定义顺序
public final void execute1() {
method1();
method2();
method3();
}
// 扩展 -> 还可以这样用哦 ~~~~
public final TestModel execute2() {
TestModel model = null;
if (this.name.equals("A")) {
model = method1();
} else if (this.name.equals("B")) {
model = method2();
} else if (this.name.equals("C")) {
model = method3();
}
return model;
}
}
public class Mr_APerson extends PersonDaily {
public Mr_APerson(String name) {
super.name = name;
}
@Override
protected TestModel method1() {
return new TestModel();
}
@Override
protected TestModel method2() {
return new TestModel();
}
@Override
protected TestModel method3() {
return new TestModel();
}
}
public class Visitor {
public void visit(PersonDaily person){
if (person instanceof Mr_APerson) person.execute2();
}
public static void main(String[] args) {
Visitor visitor = new Visitor();
visitor.visit(new Mr_APerson("A"));
}
优缺点
优点
- 在父类中提取了公共的部分代码,便于代码复用。
- 能够灵活应对子类重写的方法,及扩展的方法,符合程序的开闭原则
缺点
- 由于继承关系自身的缺点,如果父类添加新的抽象方法,则所有子类都要改一遍。
- 对每个不同的实现都需要定义一个子类,这会导致类的个数增加,系统更加庞大,设计也更加抽象,间接地增加了系统实现的复杂度。