Java23种设计模式【19】----》模板方法模式(template method)

一、场景

流程骨架清楚,但具体实现还不清楚

如吃饭,吃饭流程都知道,但具体吃什么饭不清楚

二、模板方法模式介绍

定义好骨架,但具体某个方法该怎么调不知道

Java23种设计模式【19】----》模板方法模式(template method)

三、核心

Java23种设计模式【19】----》模板方法模式(template method)

四、方法回调(钩子方法)

Java23种设计模式【19】----》模板方法模式(template method)

五、什么时候用模板方法模式

Java23种设计模式【19】----》模板方法模式(template method)

六、开发中的场景

Java23种设计模式【19】----》模板方法模式(template method)

七、代码实现

1、模板类

案例:银行办理业务

**钩子方法:未实现的方法,交由子类来实现

**业务方法:模板方法中的调用的钩子方法定义为抽象方法

**模板方法加上final表示子类不能重写

Java23种设计模式【19】----》模板方法模式(template method)

2、取钱类,实现模板类

Java23种设计模式【19】----》模板方法模式(template method)

3、测试1

Java23种设计模式【19】----》模板方法模式(template method)

结果:

Java23种设计模式【19】----》模板方法模式(template method)

测试2:

创建匿名内部类,存钱类

Java23种设计模式【19】----》模板方法模式(template method)

结果:

Java23种设计模式【19】----》模板方法模式(template method)