简介
Template Method Pattern 被认为是一种"作用于实现"(behavioral pattern)的设计模式,这是因为它关注的是算法的实现方式和步骤,而不是对象之间的组合或类之间的继承关系。在这种模式中,主要关心的是如何定义一个算法的骨架,并将一些具体步骤的实现延迟到子类。这种模式允许子类在不改变算法结构的情况下重新定义算法中的某些步骤。
背景
问题介绍
Coffee 和 Tea 制作过程有着自己的行为
原始实现
- Coffee类实现
- Tea 类实现
设计
3.
hook
hooks 方法允许子类通过选择性地覆盖或实现这些方法,来对算法的某些步骤进行自定义。
Use abstract methods when your subclass MUST provide an implementation of the method or step in the algorithm.
Use hooks when that part of the algorithm is optional. With hooks, a subclass may choose to implement that hook, but it doesn’t have to.