:模板方法模式:Beverage
#ifndef __COFFINEBEVERAGE_H__ #define __COFFINEBEVERAGE_H__ #include <iostream> using namespace std; class Beverage { public: Beverage(){} virtual ~Beverage(){} void Prepare() { BoilWater(); Brew(); PourInCup(); AddCondiments(); } virtual void Brew() = 0; virtual void AddCondiments() = 0; void BoilWater() { cout << "Boil Water." << endl; } void PourInCup() { cout << "Pour In Cup." << endl; } }; class Coffe : public Beverage { public: Coffe(){} virtual ~Coffe(){} virtual void Brew() { cout << "Dripping Water through filter" << endl; } virtual void AddCondiments() { cout << "Add sugar and milk" << endl; } }; class Tea : public Beverage { public: Tea(){} virtual ~Tea(){} virtual void Brew() { cout << "Steeping the tea." << endl; } virtual void AddCondiments() { cout << "Add lemon." << endl; } }; #endif
#include <iostream> #include "Beverage.h" using namespace std; int main() { Beverage *t = new Tea(); t->Prepare(); cout << "==========Coffe============" << endl; Beverage *c = new Coffe(); c->Prepare(); return 0; }