HeadFirst设计模式之Singleton【孤独者模式】

//Chocolate.hpp

#ifndef	_HFDP_CPP_SINGLETON_CHOCOLATE_HPP_
#define _HFDP_CPP_SINGLETON_CHOCOLATE_HPP_

#include "../../Standard.h"
#include "chocolateboiler.hpp"

#endif



//ChocolateBoiler.hpp


#ifndef	_HFDP_CPP_SINGLETON_CHOCOLATE_BOILER_HPP_
#define _HFDP_CPP_SINGLETON_CHOCOLATE_BOILER_HPP_

#include "Chocolate.hpp"

namespace HeadFirstDesignPatterns {
namespace Factory {
namespace Singleton {

class ChocolateBoiler {

	private: static ChocolateBoiler* _uniqueInstance;
	private: bool _empty;
	private: bool _boiled;
  
	private: ChocolateBoiler( const ChocolateBoiler& ); // Disable copy constructor
	private: void operator=( const ChocolateBoiler& ); // Disable assignment operator

	private: ChocolateBoiler() {
		_empty = true;
		_boiled = false;
	}
	private: ~ChocolateBoiler() {
		_uniqueInstance = 0;
	}
  	public: static ChocolateBoiler* getInstance() {
		if( _uniqueInstance == 0 ) {
			std::cout << "Creating unique instance of Chocolate Boiler" << std::endl;
			_uniqueInstance = new ChocolateBoiler();
		}
		std::cout << "Returning instance of Chocolate Boiler"<< std::endl;
		return _uniqueInstance;
	}
	public: void fill() {	// fill the boiler with a milk/chocolate mixture
		if( isEmpty() ) {
			_empty = false;
			_boiled = false;
		}
	}
	public: void drain() {	// drain the boiled milk and chocolate
		if( !isEmpty() && isBoiled() ) {
			_empty = true;
		}
	}
	public: void boil() {	// bring the contents to a boil
		if( !isEmpty() && !isBoiled() ) {
			_boiled = true;
		}
	}
	public: bool isEmpty() const {
		return _empty;
	} 
	public: bool isBoiled() const {
		return _boiled;
	}
};

} // namespace Singleton
} // namespace Factory
} // namespace HeadFirstDesignPatterns

#endif 


//chocolate.cpp


#include "Chocolate.hpp"

using namespace HeadFirstDesignPatterns::Factory::Singleton;

ChocolateBoiler* ChocolateBoiler::_uniqueInstance = 0;

int main( int argc, char* argv[] ) {

	ChocolateBoiler* boiler = ChocolateBoiler::getInstance();
	boiler->fill();
	boiler->boil();
	boiler->drain();

	// will return the existing instance
	ChocolateBoiler* boiler2 = ChocolateBoiler::getInstance();

	if( boiler == boiler2 )
		std::cout << "Got same boiler" << std::endl;
	else
		std::cout << "Oh oh! got a different boiler" << std::endl;

	return 0;
}



以上程序中只包含一个类,这就是孤独者模式的基本原理,输出如下:



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值