模板方法模式:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。——《HEAD FIRST 设计模式》
我的C++代码:
h:
#ifndef DESIGN_TEMPLATE_H_ #define DESIGN_TEMPLATE_H_ 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_TEMPLATE_H_
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; }
个人感悟:待留。