First head 设计模式学习c++实现------模板方法模式(Template method pattern)

来源:互联网 发布:win10 10核优化 编辑:程序博客网 时间:2024/06/06 05:31

模板方法模式:
在一个方法中定义一个算法的骨架,而将一些步骤推迟到子类中。
这里写图片描述

/* * CaffeineBeverage.h * *  Created on: Aug 16, 2017 *      Author: gwwu */#ifndef CAFFEINEBEVERAGE_H_#define CAFFEINEBEVERAGE_H_#include <iostream>using namespace std;class CaffeineBeverage {public:    void prepareRecipe(){        boilWater();        brew();        pourInCup();        addCondiments();    }    virtual void brew() = 0;    virtual void addCondiments() = 0;    void boilWater() {        cout << "Boiling water" << endl;    }    void pourInCup() {        cout << "Pouring into cup" << endl;    }    virtual ~CaffeineBeverage() {}};class Tea : public CaffeineBeverage {public:    void brew() {        cout << "Steeping the tea" << endl;    }    void addCondiments() {        cout << "Adding Lemon" << endl;    }};class Coffee : public CaffeineBeverage {public:    void brew() {        cout << "Dripping Coffee through filter" << endl;    }    void addCondiments() {        cout << "Adding Sugar and Milkl" << endl;    }};#endif /* CAFFEINEBEVERAGE_H_ */
//============================================================================// Name        : Template_method.cpp// Author      : gwwu// Version     :// Copyright   : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================#include <iostream>using namespace std;#include "CaffeineBeverage.h"int main() {    Tea tea;    tea.prepareRecipe();    Coffee coffee;    coffee.prepareRecipe();    return 0;}

运行结果:

这里写图片描述

阅读全文
0 0
原创粉丝点击