设计模式:10 模板方法模式

来源:互联网 发布:2017淘宝摇一摇在哪里 编辑:程序博客网 时间:2024/05/19 21:00

模板方法模式:

问题出现:

用了继承,应该成为子类的模板,所有重复的代码要上升到父类去,而不是让每个子类都重复。

解决方法:

我们要完成在某一细节层次一致的过程,但个别步骤在更详细的层次上的实现可能不同时,用模板方法模式处理

含义:定义一个操作中算法的骨架,将步骤延迟到子类中。模板方法使得子类可以不改变算法结构即可重定义算法的特定步骤。

 

模板方法模式:把不变行为搬移到超类,去除子类中重复代码。模板方法模式提供代码复用。

 

main.cpp

#include <iostream>#include <stdlib.h>#include "Beverage.h"#include "Coffee.h"#include "Tea.h"using namespace std;void process(){cout << "冲杯咖啡:" << endl;Coffee coffee;coffee.prepareRecipe();cout << "\n冲杯茶:" << endl;Tea tea;tea.prepareRecipe();}int main(int argc,char* argv[]){process();system("pause");return 0;}


Tea.h

#ifndef TEA_H#define TEA_H#include "beverage.h"class Tea :public Beverage{public:Tea(void);~Tea(void);protected:void brew();void addCondiments();};#endif

Tea.cpp

#include "Tea.h"#include <iostream>using namespace std;Tea::Tea(void){}Tea::~Tea(void){}void Tea::brew(){cout << "用沸水浸泡茶叶" << endl;}void Tea::addCondiments(){cout << "加柠檬" << endl;}


Coffee.h

#ifndef COFFEE_H#define COFFEE_H#include "beverage.h"class Coffee :public Beverage{public:Coffee(void);~Coffee(void);protected:void brew();void addCondiments();};#endif


Coffee.cpp

#include "Coffee.h"#include <iostream>using namespace std;Coffee::Coffee(void){}Coffee::~Coffee(void){}void Coffee::brew(){cout << "用沸水冲泡咖啡" << endl;}void Coffee::addCondiments(){cout << "加糖和牛奶" << endl;}


Beverage.h

#ifndef BEVERAGE_H#define BEVERAGE_Hclass Beverage{public:Beverage(void);virtual ~Beverage(void);//咖啡因饮料冲泡法void prepareRecipe();protected:void boilWater();//把水煮沸virtual void brew();//冲泡,把容易发生变化的做成虚函数void poulInCup();//把咖啡因饮料倒进杯子virtual void addCondiments();//加调料};#endif


Beverage.cpp

#include "Beverage.h"#include <iostream>using namespace std;Beverage::Beverage(void){}Beverage::~Beverage(void){}//关键:模板方法模式 父类抽象出算法框架,对于不变的部分自己实现;对于改变的部分设置为虚函数,由子类实现void Beverage::prepareRecipe(){boilWater();brew();poulInCup();addCondiments();}void Beverage::boilWater()//把水煮沸{cout << "把水煮沸" << endl;}void Beverage::brew()//冲泡,把容易发生变化的做成虚函数{}void Beverage::poulInCup()//把咖啡因饮料倒进杯子{cout << "倒进杯子" << endl;}void Beverage::addCondiments()//加调料{}


 

0 0