模板模式
定义一个操作中的算法的骨架,将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可以重定义该算法的某些特定步骤!
适用性
1.一次性实现算法中的不变部分,并且将可变的行为留给子类来实现
2.各子类中公共的行为应被提取出来并且集中到一个公共父类中以避免代码重复。首先识别现有代码中的不同之处,并且将不同之处分离为新的操作。最后,用一个调用这些新的操作的模板方法来替换这些不同的代码
3.控制子类扩展
参与者
1.AbstractClass
定义抽象的原语操作,本例中就是printInfo(),然后在子类中对它们进行重定义,以实现一个算法的各个步骤,
定义一个模板方法update(),然后在里面调用上面的那个原语操作:
2.ConcreteClass
上述抽象类的一个具体实现
一个例子
1.AbstractClass
public abstract class Template {
public abstract void printInfo();
public void update() {
System.out.println("the result is listed:");
for (int i = 0; i < 10; i++)
printInfo();
}
}
2.ConcreteClass
public class ConcreteTemplate extends Template {
@Override
public void printInfo() {
System.out.println("this is the completed of the subclass!!!");
}
}
Test
public class Test {
public static void main(String[] args) {
Template t = new ConcreteTemplate();
t.update();
}
}
result
the result is listed:
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!