模板方法模式:
在一个方法中定义一个算法的骨架,而将一些步骤推迟到子类中。
/*
* 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;
}
运行结果: