设计模式: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
- 设计模式:10 模板方法模式
- 大话设计模式10----模板方法模式
- 设计模式:模板方法模式
- 设计模式 - 模板方法模式
- 设计模式:模板方法模式
- 设计模式 模板方法模式
- 设计模式--模板方法模式
- 设计模式-【模板方法模式】
- 设计模式: 模板方法模式
- 设计模式- 模板方法模式
- 设计模式 - 模板方法模式
- 设计模式 - 模板方法模式
- 设计模式-模板方法模式
- 设计模式-模板方法模式
- 设计模式---模板方法模式
- 设计模式-模板方法模式
- 设计模式--模板方法模式
- 设计模式-模板方法模式
- 【解惑】一文告诉你,该学R还是Python!
- [UVA 1629]Cake slicing[记忆化搜索]
- 设计模式: 9 原型模式
- HDU1556-Color the ball-线段树成段更新入门题/前缀和
- 干货 知识图谱研究青年学者研讨会在清华大学顺利召开刘知远 报告题目:大规模知识图谱表示学习的研究趋势与挑战
- 设计模式:10 模板方法模式
- 知识图谱技术原理介绍
- 初次尝试用devc++ 写自定义头文件 遇到的问题
- 知识图谱——机器大脑中的知识库
- _DataStructure_C_Impl:Dijkstra算法求最短路径
- Deep Learning 和 Knowledge Graph 引爆大数据革命
- 设计模式: 11 迪米特法则
- _DataStructure_C_Impl:Floyd算法求有向网N的各顶点v和w之间的最短路径
- _DataStructure_C_Impl:在图G中求距离顶点v0最短路径为k的所有顶点