模板方法模式(Template)

本文深入探讨了模板方法模式的概念、作用以及其实现方式,并通过具体代码实例展示了如何利用钩子机制来定制算法的特定部分。通过对比策略模式,阐述了两者在封装算法方面的不同之处。
模板方法模式:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。

当我们要完成在某一细节层次一致的一个过程或一系列步骤,但其个别步骤在更详细的层次上的实现可能不同时,我们通常考虑用模板方法模式来处理.

钩子(hook):是一种被声明在抽象类中的方法,但只有空的或者默认的实现。钩子的存在,可以让子类有能力对算法的不同点进行挂钩。

要点:
1.“模板方法“定义了算法的步骤,把这些步骤的实现延迟到子类
2.模板方法模式为我们提供了一种代码复用的重要技巧
3.模板方法的抽象类可以定义具体方法,抽象方法和钩子
4.抽象方法由子类实现
5.钩子是一种方法,它在抽象类中不做事,或者只做默认的事情,子类可以选择要不要去覆盖它
6.为了防止子类改变模板方法中的算法,可以将模板方法声明为const
7.好莱坞原则告诉我们,将决策权放在高层模块中,以便决定如何以及何时调用低层模块
8.策略模式和模板方法模式都封装算法,一个用组合,一个用继承
9.工厂方法是模板方法的一种特殊版本

设计原则:
别找我,我会找你,由超类主控一切,当它们需要的时候,自然会去调用子类,这就跟好莱坞一样

[img]http://dl.iteye.com/upload/attachment/511569/c0f28cdc-ee62-37bf-9cd6-431740dfcc57.png[/img]

CaffeineBeverage.h

#ifndef CAFFEINEBEVERAGE_H
#define CAFFEINEBEVERAGE_H
#include <iostream>
using namespace std;
class CaffeineBeverage{
public:
virtual void boilWater()const{
cout << "boil water" << endl;
}
virtual void brew()const=0;
virtual void pourInCup()const{
cout << "pour in cup" << endl;
}
virtual void addCondiments()const=0;
//this is a hook
virtual bool needCondiments(){
return true;
}
void prepareRecipe(){
boilWater();
brew();
pourInCup();
if(needCondiments()){
addCondiments();
}
}
};

#endif // CAFFEINEBEVERAGE_H



Coffee.h

#ifndef COFFEE_H
#define COFFEE_H
#include "CaffeineBeverage.h"

class Coffee:public CaffeineBeverage{
public:
void brew()const{
cout << "Dripping Coffee through filter" << endl;
}
void addCondiments()const{
cout << "Adding sugar" << endl;
}
};

#endif // COFFEE_H




#ifndef TEA_H
#define TEA_H
#include "CaffeineBeverage.h"
#include <string>
class Tea:public CaffeineBeverage{
public:
void brew()const{
cout << "steeping the tea" << endl;
}
void addCondiments()const{
cout << "Adding Lemond" << endl;
}
bool needCondiments(){
string t;
cout << "Need a Lemond?Y:N" << endl;
cin >> t ;
if(t=="y"||t=="Y")
return true;
return false;
}
};

#endif // TEA_H



main.cpp

#include "CaffeineBeverage.h"
#include "Coffee.h"
#include "Tea.h"

int main()
{
CaffeineBeverage* cb = new Tea;
cb->prepareRecipe();
cb = new Coffee;
cb->prepareRecipe();
}

boil water
steeping the tea
pour in cup
Need a Lemond?Y:N
N
Adding Lemond
boil water
Dripping Coffee through filter
pour in cup
Adding sugar





来个简化版:


class Interface
{
public:
virtual void method0()=0;
void method1(){};
void method2(){};
void method3(){};
void method4(){};
};

class A:public Interface
{
void method0(){}
};

class Model
{
public:
Model(){
m = new A;
}

~Model(){}

void run()
{
m->method0();
m->method1();
m->method2();
m->method3();
m->method4();
}
private:
Interface* m;
};


int main()
{
Model model;
model.run();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值