design_pattern_template

本文介绍模板模式的设计原理及实现步骤,通过制作咖啡和茶的例子,展示了如何定义算法骨架并在子类中实现特定步骤,保持算法结构不变的同时允许子类定制化。

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.

  1. Examine the algorithm, and decide which steps are standard andwhich steps are peculiar to each of the current classes.
  2. Define a new abstract base class to host the "don't call us,we'll call you" framework.
  3. Move the shell of the algorithm (now called the "templatemethod") and the definition of all standard steps to the new baseclass.
  4. 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++).
  5. Invoke the hook method(s) from the template method.
  6. Each of the existing classes declares an "is-a" relationshipto the new abstract base class.
  7. Remove from the existing classes all the implementationdetails that have been moved to the base class.
  8. 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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值