設計模式C++ : 模板方法模式
模板方法模式:在一個方法中定義一個算法的骨架,而將一些步驟延遲到子類中。模板方法使得子類可以在不改變算法結構的情況下,重新定義算法中的某些步驟。——《HEAD FIRST 設計模式》
我的C++代碼:
h:
#ifndef DESIGN_TEMPLATEHdefine DESIGN_TEMPLATEH
namespace templated{ class CaffeineBeverage { public: void prepareRecipe(); void boilWater(); void pourInCup(); public: virtual void brew() = 0; virtual void addCondiments() = 0; }; class Tea : public CaffeineBeverage { public: virtual void brew(); virtual void addCondiments(); }; class Coffee : public CaffeineBeverage { public: virtual void brew(); virtual void addCondiments(); }; }
endif // DESIGN_TEMPLATEH</pre>
cpp:
#include "template.h"include <iostream>
using namespace templated; void CaffeineBeverage::prepareRecipe() { boilWater(); brew(); pourInCup(); addCondiments(); } void CaffeineBeverage::boilWater() { std::cout << "boil water!" << std::endl; } void CaffeineBeverage::pourInCup() { std::cout << "pour in cup!" << std::endl; } void Tea::brew() { std::cout << "tea brew!" << std::endl; } void Tea::addCondiments() { std::cout << "tea add condiments!" << std::endl; } void Coffee::brew() { std::cout << "coffee brew!" << std::endl; } void Coffee::addCondiments() { std::cout << "coffee add condiments!" << std::endl; }</pre>
原文 http://www.ituring.com.cn/article/200355