模板模式(Template Pattern)
模板模式(定义了一个算法的步骤,并允许子类为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤)
-
优点: 1、利用模板方法将相同处理逻辑的代码放到抽象父类中,可以提高代码的复用性 2、将不同的代码不同的子类中,通过对子类的扩展增加新的行为,提高代码的扩展性 缺点: 1、每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大 2、继承关系自身缺点,如果父类添加新的抽象方法,所有子类都要改一遍 使用场景: 1、有多个子类共有的方法,且逻辑相同 2、重要的、复杂的方法,可以考虑作为模板方法 模板方法模式包含以下主要角色: 抽象模板类:由一个模板方法、具体方法、抽象方法、钩子方法构成 模板方法:按某种顺序调用其包含的方法(具体方法、抽象方法、钩子方法) 具体方法:在抽象类中已经实现,在具体子类中可以继承或重写它 抽象方法:在抽象类中声明,由具体子类实现 钩子方法:在抽象类中已经实现,包括用于判断的逻辑方法和需要子类重写的空方法两种 具体模板子类:实现抽象类中所定义的抽象方法和钩子方法 类图: 代码实现:
抽象模板类
/**
* 抽象模板类
*/
public abstract class Template {
// 模板方法
final public void templateMethod() {
// 具体方法
this.definiteMethod();
// 抽象方法1
this.abstractMethod1();
// 钩子方法1
this.HookMethod1();
// 钩子方法2
if (this.HookMethod2()) {
System.out.println("钩子方法2返回为true");
}
}
// 具体方法
private void definiteMethod() {
System.out.println("具体方法被执行!");
}
// 抽象方法1
abstract void abstractMethod1();
//钩子方法1
void HookMethod1() {
System.out.println("钩子方法1被执行");
}
// 钩子方法1
boolean HookMethod2() {
System.out.println("钩子方法2被执行");
return true;
}
}
具体模板子类
/**
* 具体模板子类
*/
public class ConcreteTemplate extends Template {
@Override
void abstractMethod1() {
System.out.println("抽象方法1被执行");
}
// 重写钩子方法1
void HookMethod1() {
System.out.println("钩子方法1被重写");
}
// 重写钩子方法1
boolean HookMethod2() {
System.out.println("钩子方法2被重写");
return true;
}
}
** 测试**
public class Test {
public static void main(String[] args) {
Template template = new ConcreteTemplate();
template.templateMethod();
}
}
// 运行结果
具体方法被执行!
抽象方法1被执行
钩子方法1被重写
钩子方法2被重写
钩子方法2返回为true
