设计模式:模板方法模式(8)C++版

模板方法模式:封装算法在一个抽象类中,在其子类中进行全部或部分的真正的实现


C++示例代码如下:

#include "stdafx.h"

#include <string>
#include <iostream>

using namespace std;

/*
* CONTENTS: DESIGN PATTERN, TEMPLATE METHOD PATTERN
*   AUTHOR: YAO H. WANG
*     TIME: 2013-11-6 16:43:47
*  EDITION: 1
*     LINK: http://blog.csdn.net/yaohwang  
*
* ALL RIGHTS RESERVED!
*/

class CaffineBeverageWithHook
{
public:
	virtual void prepareRecipe() final
	{
		boilWater();
		brew();
		pourInCup();
		if(customerWantsCondiments())
		{
			addCondiments();
		}
	}

	void boilWater()
	{
		cout << "Boiling water" << endl;
	}

	virtual void brew() = 0;

	void pourInCup()
	{
		cout << "Pouring into cup" << endl;
	}

	//hook
	virtual bool customerWantsCondiments()
	{
		return true;
	}

	virtual void addCondiments() = 0;
};

class CoffeeWithHook: public CaffineBeverageWithHook
{
public:
	void brew()
	{
		cout << "Dripping Coffee through filter" << endl;
	}

	void addCondiments()
	{
		cout << "Adding Sugar and Milk" << endl;
	}

	bool customerWantsCondiments()
	{
		string answer = getUserInput();

		if('y' == answer[0])
			return true;
		else
			return false;
	}

	string getUserInput()
	{
		string answer;
		cout << "Would you like milk and sugar with your coffee (y/n)?" << endl;
		cin >> answer;
		return answer;
	}
};

class TeaWithHook: public CaffineBeverageWithHook
{
public:
	void brew()
	{
		cout << "Steeping the tea" << endl;
	}

	void addCondiments()
	{
		cout << "Adding Lemon" << endl;
	}

	bool customerWantsCondiments()
	{
		string answer = getUserInput();

		if('y' == answer[0])
			return true;
		else
			return false;
	}

	string getUserInput()
	{
		string answer;
		cout << "Would you like lemon with your tea (y/n)?" << endl;
		cin >> answer;
		return answer;
	}
};

//测试
void main()
{
	TeaWithHook teaHook;
	CoffeeWithHook coffeeHook;

	cout << "Making tea..." << endl;
	teaHook.prepareRecipe();

	cout << "\nMaking coffee..." << endl;
	coffeeHook.prepareRecipe();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值