单件模式确保一个类只有一个实例,并提供一个全局访问点。
确定在性能和资源上的限制,然后小心地选择适当的方案来实现单件,以解决多线程的问题。
代码链接:
单件模式类图:
源代码:
#ifndef CHOCOLATEBOILER_H#define CHOCOLATEBOILER_H#include测试代码:class ChocolateBoiler{ private: ChocolateBoiler() { empty = true; boiled = false; } ~ChocolateBoiler() { uniqueInstance = 0; } ChocolateBoiler( const ChocolateBoiler& ); void operator=( const ChocolateBoiler& ); 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; } void fill() { if(isEmpty()) { empty = false; boiled =false; } } void drain() { if(!isEmpty() && isBoiled()) { empty = true; } } void boil() { if(!isEmpty() && !isBoiled()) { boiled = true; } } bool isEmpty() { return empty; } bool isBoiled() { return boiled; } protected: private: bool empty; bool boiled; static ChocolateBoiler* uniqueInstance;};#endif // CHOCOLATEBOILER_H
#include "ChocolateBoiler.h"ChocolateBoiler* ChocolateBoiler::uniqueInstance = 0;int main(){ ChocolateBoiler* boiler = ChocolateBoiler::getInstance(); boiler->fill(); boiler->boil(); boiler->drain(); ChocolateBoiler *boiler2= ChocolateBoiler::getInstance(); if(boiler == boiler2) std::cout<<"Got same boiler"<
测试结果如下: