第十一章节 - 模板方法模式

 

模板方法设计模式 - 章节

 

概念
▪代码重用
▪常见的包/框架
▪IOC
▪算法强调
▪ Examples:
- java.util.Collections#sort()
- java.util.AbstractList#indexOf()


设计注意事项
Abstract Base class
Base calls Child
Hooks
Operations
AbstractBase, ConcreteClass


UML图
第十一章节 - 模板方法模式

 

例子:Collections#sort
第十一章节 - 模板方法模式

 

练习:模板方法模式
OrderTemplate, WebOrder, StoreOrder
Create Template Method
第十一章节 - 模板方法模式

第十一章节 - 模板方法模式

第十一章节 - 模板方法模式

第十一章节 - 模板方法模式

 

陷阱
▪限制访问
▪混乱的层次结构
▪困难的程序流程


对比

模板方法模式
▪相同的算法
▪基于类
▪编译时

策略模式
▪ Algorithm per Strategy
▪ Interface based
▪ Run time


模板方法模式总结
• 保证算法的依从性
• IoC
• 更容易实现