模板设计模式
- 目的
- 将做N件事情的步骤中重复的部分抽离出来,形成父类,将特殊的步骤交由子类去实现,形成模板,
- 优缺点
- 优:1、封装不变部分,扩展可变部分。 2、提取公共代码,便于维护。 3、行为由父类控制,子类实现。
- 缺:每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。
- 应用实例
1、在造房子的时候,地基、走线、水管都一样,只有在建筑的后期才有加壁橱加栅栏等差异。
2、多线程Thread就是模板设计模式中的父类,新的线程只要实现Thread中的run方法来实现特殊的步骤,start()方法则是通过本地方法start0()来调用run方法。 - 代码实现
public class TemplateMethod {
public final void start(String message){
System.out.println("###########");
run(message);
System.out.println("###########");
}
abstract void run();
public static void main(String[] args) {
TemplateMethod templateMethod = new TemplateMethod(){
@Override
protected void run(String message) {
super.run(message);
System.out.println("#" + message +"#");
}
};
TemplateMethod templateMethod1 = new TemplateMethod(){
@Override
protected void run(String message) {
super.run(message);
System.out.println("*" + message + "*");
}
};
templateMethod.start("hello world");
templateMethod1.start("hello world");
}
}
- 运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d648ff1218cfdd0013262ca2d6fc033c.png)