This post implement template pattern in <Head First Design Patterns>. Template pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm structure.
- Examine the algorithm, and decide which steps are standard andwhich steps are peculiar to each of the current classes.
- Define a new abstract base class to host the "don't call us,we'll call you" framework.
- Move the shell of the algorithm (now called the "templatemethod") and the definition of all standard steps to the new baseclass.
- Define a placeholder or "hook" method in the base class foreach step that requires many different implementations. Thismethod can host a default implementation – or – it canbe defined as abstract (Java) or pure virtual (C++).
- Invoke the hook method(s) from the template method.
- Each of the existing classes declares an "is-a" relationshipto the new abstract base class.
- Remove from the existing classes all the implementationdetails that have been moved to the base class.
- The only details that will remain in the existing classeswill be the implementation details peculiar to each derived class.
class CaffeineBeverage {
public:
virtual void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
virtual void brew() = 0;
virtual void addCondiments() = 0;
void boilWater() {
std::cout << "Boiling water" << std::endl;
}
void pourInCup() {
std::cout << "Pouring into cup" << std::endl;
}
};
class Coffee : public CaffeineBeverage {
public:
virtual void brew() {
std::cout << "Dripping Coffee through filter" << std::endl;
}
virtual void addCondiments() {
std::cout << "Adding Sugar and Milk" << std::endl;
}
};
class Tea : public CaffeineBeverage {
public:
virtual void brew() {
std::cout << "Steeping the tea" << std::endl;
}
virtual void addCondiments() {
std::cout << "Adding Lemon" << std::endl;
}
};main function is
#include <iostream>
#include <./coffeeinbeverage.hpp>
int main()
{
Tea* tea = new Tea();
Coffee* coffee = new Coffee();
std::cout << std::endl << "Making tea..." << std::endl;
tea->prepareRecipe();
std::cout << std::endl << "Making coffee..." << std::endl;
coffee->prepareRecipe();
delete tea;
tea = NULL;
delete coffee;
coffee = NULL;
return 0;
}
本文介绍模板模式的设计原理及实现步骤,通过制作咖啡和茶的例子,展示了如何定义算法骨架并在子类中实现特定步骤,保持算法结构不变的同时允许子类定制化。
461

被折叠的 条评论
为什么被折叠?



