設計模式:模板方法模式(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();
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章