Menu

  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay
  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay

模板方法模式

6
Nov
2006

模板方法模式

By Alex
/ in Architecture
/ tags 设计模式
0 Comments
模式定义

在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。在GOF95中模板方法被归类为行为模式。

模式结构与说明

patterns_TemplateMethodPattern

  1. templateMethod为模板方法,它组织调用若干原语(Primitive)方法、具体方法和钩子方法,形成算法骨架:
    Java
    1
    2
    3
    4
    5
    6
    7
    public void templateMethod()
    {
        primitiveOperation1();
        primitiveOperation2();
        concreteOperation();
        hook();
    }
  2. primitiveOperation*为若干原语方法,在抽象类中作为抽象方法出现,因此模板方法与这些基本操作是解耦的
  3. 抽象类中可以包含 final concreteOperation() 这样的具体方法, 禁止覆盖,可以被模板或者子类直接调用
  4. 抽象类中可以包含 hook() 这样的钩子方法,默认什么都不做,子类可以覆盖它,从而在算法的不同点进行挂钩。如果子类的算法步骤是可选的,可以使用钩子方法代替抽象方法。钩子方法的命名一般是doXxx的形式,例如HttpServlet的doGet/doPost
  5. 具体类需要实现模板方法需要的所有原语方法

模板方法的优点:

  1. 实现代码复用:通过抽取子类的公共功能并放入到模板方法中实现复用

模板方法的缺点:

  1. 算法骨架不易于升级,应当注意仅把确定不会变化的部分放到模板方法中

模板方法的适用时机:

  1. 需要固定算法骨架的时候
  2. 需要抽取子类公共功能,避免代码重复时
  3. 需要控制子类的扩展点时
应用举例

有闲的时候我喜欢自己炒菜吃,健康又实惠,家常菜的烹饪过程基本上是简单的套路:准备食材、烹调、装盘。要是能设计个机器女仆来帮我炒菜就好了,比起炒来我更喜欢吃:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Maid
{
    public:
        void cook( string foodType )
        {
            if ( foodType == "鱼香肉丝" )
            {
                cout << "葱白切丝" << endl;
                cout << "生姜切末" << endl;
                cout << "准备油盐酱醋" << endl;
 
                cout << "泡辣椒切末" << endl;
                cout << "猪里脊肉切细丝腌制" << endl;
                cout << "绿尖椒、胡萝卜、冬笋分别切细丝" << endl;
 
                cout << "锅中放少许油,放入葱、姜、蒜末炒香,放入泡辣辣末炒出红油" << endl;
                cout << "放入胡萝卜、冬笋、木耳翻炒2分钟,放入尖椒翻炒均匀" << endl;
                cout << "放入炒好的肉丝迅速翻炒均匀" << endl;
 
                count<< "装盘,主人请享用" << endl;
            }
            else if ( foodType == "凉拌黄瓜" )
            {
                cout << "蒜捣成泥" << endl;
                cout << "准备油盐酱醋" << endl;
 
                cout << "黄瓜拍碎" << endl;
                cout << "调入酱油、蒜泥、醋搅拌" << endl;
                count<< "装盘,主人请享用" << endl;
            }
            else if(……){……}
        }
};

女仆炒的菜味道不错,就是添加菜谱太麻烦了,我得不断添加else-if,不断的刷写女仆主板固件。 

前面已经提到过了,炒菜基本上是三个步骤,我们家乡菜大部分都是准备葱姜蒜,切好肉、蔬菜,然后热油、炒制,最后装盘,既然算法步骤如此固定,何不引入模板方法模式,简化添加菜谱的难度呢?我决定引入可拔插的女仆芯片(MaidChip),每种芯片负责一种菜品:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//厨房女仆芯片
class AbstractMaidChip
{
    public:
        virtual void ~AbstractMaidChip()
        {
        }
        //炒菜,模板方法,规定了炒菜的基本步骤
        void cook()
        {
            prepareFoodMaterial(); //准备食材,允许子类变更,提供了缺省适配的部分
            doCook(); //烹调,子类动态扩展的部分
            dishUp(); //起锅装盘,固定的算法部分
        }
    private:
        void dishUp()
        {
            cout << "装盘,主人请享用" << endl;
        }
    protected:
        virtual void prepareFoodMaterial()
        {
            cout << "葱白切丝" << endl;
            cout << "生姜切末" << endl;
            cout << "准备油盐酱醋" << endl;
        }
        virtual void doCook() = 0;
};
//鱼香肉丝芯片
class YuShiangShreddedPorkMaidChip : public AbstractMaidChip
{
    protected:
        virtual void prepareFoodMaterial()
        {
            //继承通用步骤
            AbstractMaidChip::prepareFoodMaterial();
            //鱼香肉丝还要准备额外的食材:
            cout << "泡辣椒切末" << endl;
            cout << "猪里脊肉切细丝腌制" << endl;
            cout << "绿尖椒、胡萝卜、冬笋分别切细丝" << endl;
        }
        virtual void doCook()
        {
            cout << "锅中放少许油,放入葱、姜、蒜末炒香,放入泡辣辣末炒出红油" << endl;
            cout << "放入胡萝卜、冬笋、木耳翻炒2分钟,放入尖椒翻炒均匀" << endl;
            cout << "放入炒好的肉丝迅速翻炒均匀" << endl;
        }
};
//凉拌黄瓜芯片
class saladCucumberMaidChip : public AbstractMaidChip
{
    protected:
        virtual void prepareFoodMaterial()
        {
            cout << "蒜捣成泥" << endl;
            cout << "准备油盐酱醋" << endl;
        }
        virtual void doCook()
        {
            cout << "黄瓜拍碎" << endl;
            cout << "调入酱油、蒜泥、醋搅拌" << endl;
        }
};

现在真是很方便呢,女仆主板也不要改动了,想吃新菜,只需要插一个新芯片就可以了:

C++
1
2
3
4
5
6
7
8
9
10
class Maid
{
    private:
        map<string, AbstractMaidChip*> chips;
    public:
        void cook( string foodType )
        {
            chips[foodType]->cook();
        }
};
经典应用
Java:Arrays.sort(object[])
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void sort(Object[] a) {
    Object[] aux = (Object[])a.clone();
    mergeSort(aux, a, 0, a.length, 0);
}
//mergeSort本质上是模板方法
private static void mergeSort(Object[] src, Object[] dest, int low, int high, int off) {
    int length = high - low;
    //合并排序的算法骨架
    if (length < INSERTIONSORT_THRESHOLD) {
        for (int i=low; i<high; i++)
            for (int j=i; j>low &&
         //Comparable的compareTo本质上是原语方法
         ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)  
                swap(dest, j, j-1);  //这是一个具体方法
        return;
    }
    ……
}

这个例子和经典的模板方法模式在结构上差异很大,但是注意,模板方法模式的核心是:提供一个算法,并让子类型实现某些步骤。 Arrays.sort的例子中,合并排序的算法骨架已经建好,所有子类(Comparable的)必须实现合理的compareTo方法,以支持排序。

Swing:paint()钩子方法

JFrame是Swing最基本的容器,其从java.awt.Component继承了一个paint()方法,默认paint什么都不做,它是一个钩子:

patterns_TemplateMethodPattern_Swing

RepaintManager类的paintDirtyRegions方法是个模板方法,它会遍历所有过期的组件,依次调用其paint(),JFrame的子类可以覆盖paint以提供特定的绘制行为。

Spring中的模板方法模式

Spring框架中有大量的模板方法模式的实现,例如Bean生命周期管理,就是依靠钩子方法来实现的:

Java
1
2
3
4
5
6
7
public class Bean
{
    @PostConstruct
    public void init(){}  //初始化钩子
    @PreDestroy
    public void destory(){} //销毁钩子
}

Spring中还包含了很多基于回调的模板方法变体,例如:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class JdbcTemplate
{
    //这是一个模板方法
    public <T> T execute( StatementCallback<T> action ) throws DataAccessException{
        //算法骨架
        Connection conToUse = DataSourceUtils.getConnection( getDataSource() );
        Statement stmt = conToUse.createStatement();
        applyStatementSettings( stmt );
        Statement stmtToUse = stmt;
        if ( this.nativeJdbcExtractor != null ){
            stmtToUse = this.nativeJdbcExtractor.getNativeStatement( stmt );
        }
        T result = action.doInStatement( stmtToUse ); //回调原语方法
        handleWarnings( stmt );
        return result;
    }
}
 
public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations {
    public <T> T browseSelected(final String queueName, final String messageSelector, final BrowserCallback<T> action) throws JmsException {
        return execute(new SessionCallback<T>() {
            public T doInJms(Session session) throws JMSException {
                //算法骨架
                Queue queue = (Queue) getDestinationResolver().resolveDestinationName(session, queueName, false);
                QueueBrowser browser = createBrowser(session, queue, messageSelector);
                return action.doInJms(session, browser); //回调原语方法
            }
        }, true);
    }
}
模式演变
  1. 与工厂方法结合使用:原语方法返回创建的对象
  2. 基于回调技术的模板方法比起经典的基于继承的模板方法,更加灵活、耦合度更低,但是复杂度较高
  3. 模板方法与策略模式优点类似,但是前者的核心是算法骨架的封装;后者则是整个算法的封装
← 外观模式
迭代器模式 →

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Related Posts

  • 代理模式
  • 备忘录模式
  • 适配器模式
  • 策略模式
  • 观察者模式

Recent Posts

  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
  • A Comprehensive Study of Kotlin for Java Developers
  • 背诵营笔记
  • 利用LangChain和语言模型交互
  • 享学营笔记
ABOUT ME

汪震 | Alex Wong

江苏淮安人,现居北京。目前供职于腾讯云,专注容器方向。

GitHub:gmemcc

Git:git.gmem.cc

Email:gmemjunk@gmem.cc@me.com

ABOUT GMEM

绿色记忆是我的个人网站,域名gmem.cc中G是Green的简写,MEM是Memory的简写,CC则是我的小天使彩彩名字的简写。

我在这里记录自己的工作与生活,同时和大家分享一些编程方面的知识。

GMEM HISTORY
v2.00:微风
v1.03:单车旅行
v1.02:夏日版
v1.01:未完成
v0.10:彩虹天堂
v0.01:阳光海岸
MIRROR INFO
Meta
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
Recent Posts
  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
    In this blog post, I will walk ...
  • A Comprehensive Study of Kotlin for Java Developers
    Introduction Purpose of the Study Understanding the Mo ...
  • 背诵营笔记
    Day 1 Find Your Greatness 原文 Greatness. It’s just ...
  • 利用LangChain和语言模型交互
    LangChain是什么 从名字上可以看出来,LangChain可以用来构建自然语言处理能力的链条。它是一个库 ...
  • 享学营笔记
    Unit 1 At home Lesson 1 In the ...
  • K8S集群跨云迁移
    要将K8S集群从一个云服务商迁移到另外一个,需要解决以下问题: 各种K8S资源的迁移 工作负载所挂载的数 ...
  • Terraform快速参考
    简介 Terraform用于实现基础设施即代码(infrastructure as code)—— 通过代码( ...
  • 草缸2021
    经过四个多月的努力,我的小小荷兰景到达极致了状态。

  • 编写Kubernetes风格的APIServer
    背景 前段时间接到一个需求做一个工具,工具将在K8S中运行。需求很适合用控制器模式实现,很自然的就基于kube ...
  • 记录一次KeyDB缓慢的定位过程
    环境说明 运行环境 这个问题出现在一套搭建在虚拟机上的Kubernetes 1.18集群上。集群有三个节点: ...
  • eBPF学习笔记
    简介 BPF,即Berkeley Packet Filter,是一个古老的网络封包过滤机制。它允许从用户空间注 ...
  • IPVS模式下ClusterIP泄露宿主机端口的问题
    问题 在一个启用了IPVS模式kube-proxy的K8S集群中,运行着一个Docker Registry服务 ...
  • 念爷爷
      今天是爷爷的头七,十二月七日、阴历十月廿三中午,老人家与世长辞。   九月初,回家看望刚动完手术的爸爸,发

  • 6 杨梅坑

  • liuhuashan
    深圳人才公园的网红景点 —— 流花山

  • 1 2020年10月拈花湾

  • 内核缺陷触发的NodePort服务63秒延迟问题
    现象 我们有一个新创建的TKE 1.3.0集群,使用基于Galaxy + Flannel(VXLAN模式)的容 ...
  • Galaxy学习笔记
    简介 Galaxy是TKEStack的一个网络组件,支持为TKE集群提供Overlay/Underlay容器网 ...
TOPLINKS
  • Zitahli's blue 91 people like this
  • 梦中的婚礼 64 people like this
  • 汪静好 61 people like this
  • 那年我一岁 36 people like this
  • 为了爱 28 people like this
  • 小绿彩 26 people like this
  • 彩虹姐姐的笑脸 24 people like this
  • 杨梅坑 6 people like this
  • 亚龙湾之旅 1 people like this
  • 汪昌博 people like this
  • 2013年11月香山 10 people like this
  • 2013年7月秦皇岛 6 people like this
  • 2013年6月蓟县盘山 5 people like this
  • 2013年2月梅花山 2 people like this
  • 2013年淮阴自贡迎春灯会 3 people like this
  • 2012年镇江金山游 1 people like this
  • 2012年徽杭古道 9 people like this
  • 2011年清明节后扬州行 1 people like this
  • 2008年十一云龙公园 5 people like this
  • 2008年之秋忆 7 people like this
  • 老照片 13 people like this
  • 火一样的六月 16 people like this
  • 发黄的相片 3 people like this
  • Cesium学习笔记 90 people like this
  • IntelliJ IDEA知识集锦 59 people like this
  • Bazel学习笔记 38 people like this
  • 基于Kurento搭建WebRTC服务器 38 people like this
  • PhoneGap学习笔记 32 people like this
  • NaCl学习笔记 32 people like this
  • 使用Oracle Java Mission Control监控JVM运行状态 29 people like this
  • Ceph学习笔记 27 people like this
  • 基于Calico的CNI 27 people like this
Tag Cloud
ActiveMQ AspectJ CDT Ceph Chrome CNI Command Cordova Coroutine CXF Cygwin DNS Docker eBPF Eclipse ExtJS F7 FAQ Groovy Hibernate HTTP IntelliJ IO编程 IPVS JacksonJSON JMS JSON JVM K8S kernel LB libvirt Linux知识 Linux编程 LOG Maven MinGW Mock Monitoring Multimedia MVC MySQL netfs Netty Nginx NIO Node.js NoSQL Oracle PDT PHP Redis RPC Scheduler ServiceMesh SNMP Spring SSL svn Tomcat TSDB Ubuntu WebGL WebRTC WebService WebSocket wxWidgets XDebug XML XPath XRM ZooKeeper 亚龙湾 单元测试 学习笔记 实时处理 并发编程 彩姐 性能剖析 性能调优 文本处理 新特性 架构模式 系统编程 网络编程 视频监控 设计模式 远程调试 配置文件 齐塔莉
Recent Comments
  • qg on Istio中的透明代理问题
  • heao on 基于本地gRPC的Go插件系统
  • 黄豆豆 on Ginkgo学习笔记
  • cloud on OpenStack学习笔记
  • 5dragoncon on Cilium学习笔记
  • Archeb on 重温iptables
  • C/C++编程:WebSocketpp(Linux + Clion + boostAsio) – 源码巴士 on 基于C/C++的WebSocket库
  • jerbin on eBPF学习笔记
  • point on Istio中的透明代理问题
  • G on Istio中的透明代理问题
  • 绿色记忆:Go语言单元测试和仿冒 on Ginkgo学习笔记
  • point on Istio中的透明代理问题
  • 【Maven】maven插件开发实战 – IT汇 on Maven插件开发
  • chenlx on eBPF学习笔记
  • Alex on eBPF学习笔记
  • CFC4N on eBPF学习笔记
  • 李运田 on 念爷爷
  • yongman on 记录一次KeyDB缓慢的定位过程
  • Alex on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • haolipeng on 基于本地gRPC的Go插件系统
  • 吴杰 on 基于C/C++的WebSocket库
©2005-2025 Gmem.cc | Powered by WordPress | 京ICP备18007345号-2