设计模式之模板方法模式
设计模式 Java 大约 1713 字作用
算法只在父类中,需要修改时只需修改父类的模板方法即可。
不足之处:每一个不同的实现都需要子类实现,导致类增加。
案例
抽象类
模板方法:make()
,final修饰,定义了算法骨架。
钩子方法:customerWantCondiments
,子类可视情况覆盖。
public abstract class SoyaMilk {
final void make() {
select();
if (customerWantCondiments()) {
addCondiments();
}
soak();
beat();
}
void select() {
System.out.println("选黄豆");
}
//添加不同配料
abstract void addCondiments();
void soak() {
System.out.println("开始浸泡");
}
void beat() {
System.out.println("打碎");
}
//钩子方法
boolean customerWantCondiments() {
return true;
}
}
实现类
public class RedBeanSoyaMilk extends SoyaMilk {
@Override
void addCondiments() {
System.out.println("加入红豆");
}
}
public class PeanutSoyaMilk extends SoyaMilk {
@Override
void addCondiments() {
System.out.println("加入花生");
}
}
调用
public class Client {
public static void main(String[] args) {
SoyaMilk peanutSoyaMilk = new PeanutSoyaMilk();
peanutSoyaMilk.make();
System.out.println("-------------------------");
SoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
redBeanSoyaMilk.make();
}
}
源码
org.springframework.context.ConfigurableApplicationContext
org.springframework.context.support.AbstractApplicationContext
org.springframework.context.support.AbstractRefreshableApplicationContext
org.springframework.context.support.AbstractRefreshableConfigApplicationContext
org.springframework.context.support.AbstractXmlApplicationContext
org.springframework.context.support.ClassPathXmlApplicationContext
org.springframework.context.support.AbstractRefreshableApplicationContext
阅读 2375 · 发布于 2019-12-23
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
SQL Server 修改计算机名后修改服务名阅读 1774
-
Linux 命令之查看进程线程数量阅读 5258
-
Elasticsearch 短语搜索 query->match_phrase阅读 2753
-
HTTP 携带多个 Cookie 请求阅读 2365
-
Vue sourceMap 代码混淆阅读 1048
-
Git 合并两个分支阅读 2153
-
Java 语法糖 - 可变参数阅读 782
-
Android ListView 条目点击变色阅读 2769
-
JavaScript 生成微信二维码阅读 2850
-
Arthas 启动报 ClassNotFoundException com.sun.tools.attach.VirtualMachine阅读 5232