[Design Pattern] Template Method Pattern

本文介绍了模板方法模式的基本概念,展示了如何通过定义算法骨架并允许子类实现特定步骤来实现代码复用。此外还讨论了抽象方法与钩子方法的作用及应用,并对比了策略模式与模板方法模式的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

 一. 基本的 Template Method Pattern 示例:

 

二. Template Method Pattern with hook  示例 :

 

三.  Hook 示例:

 

四.  使用 Hook :

 

Template Method Pattern 概要: 

Ø         A "template method" defines the steps of an algorithm, deferring to subclasses for the implementation of those steps.
 
Ø         The Template Method gives up an important technique for code reuse.
 
Ø         The template method's abstract class may define concrete classes, abstract classes and hooks.
 
Ø         Abstract methods are implemented by subclasses.
 
Ø         Hooks are methods that do nothing or default behavior in the abstract classes, but may be overridden in the subclass.
 
Ø         To prevent subclasses from changing the algorithm in the template method, declare the template method as final.
 
Ø         The Hollywood Principle guides us to put decision-making in high-level modules that can decide how and when to call low-level modules.
 
Ø         You'll see lots of uses of the Template Method Pattern in real world code, but don't expect it all (like any pattern) to be designed "by the book".
 
Ø         The strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition.
 
Ø         The Factory Method pattern is a specialization of Template Method.
 
 

 

摘自 Head First Design Patterns, O' REILLY

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值