Head First 设计模式 (五) 单件模式(Singleton pattern) C++实现
2013-04-11 11:15
525 查看
单件模式确保一个类只有一个实例,并提供一个全局访问点。
确定在性能和资源上的限制,然后小心地选择适当的方案来实现单件,以解决多线程的问题。
代码链接:点击打开链接
单件模式类图:
源代码:
测试代码:
测试结果如下:
原创转载注明出处
确定在性能和资源上的限制,然后小心地选择适当的方案来实现单件,以解决多线程的问题。
代码链接:点击打开链接
单件模式类图:
源代码:
#ifndef CHOCOLATEBOILER_H #define CHOCOLATEBOILER_H #include<iostream> 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"<<std::endl; else std::cout<<"Got different boler"<<std::endl; return 0; }
测试结果如下:
原创转载注明出处
相关文章推荐
- Head First 设计模式 (五) 单件模式(Singleton pattern) C++实现
- 《Head First 设计模式》例子的C++实现(5 单例模式)
- 设计模式--单件实现C++
- 《Head First 设计模式》例子的C++实现(5 单例模式)
- 《Head First 设计模式》-观察者模式C++实现
- 《Head First 设计模式》例子的C++实现(2 观察者模式)
- Head First 设计模式 (一) 策略模式(strategy pattern) C++实现
- 《Head First 设计模式》例子的C++实现(2 观察者模式)
- Head First 设计模式 (二) 观察者模式(observer pattern) C++实现
- 《Head First 设计模式》例子的C++实现(3 装饰模式)
- Head First 设计模式 C++实现
- Head First 设计模式 (六) 命令模式(Command pattern) C++实现
- Head First 设计模式 (七)适配器模式(adapter pattern) C++实现
- Head First 设计模式 (六) 命令模式(Command pattern) C++实现
- Head First 设计模式 (八) 模版方法模式(Template method pattern) C++实现
- Head First 设计模式 (四) 工厂模式(factory pattern) C++实现
- 《Head First 设计模式》例子的C++实现(适配器模式)
- Head First 设计模式 (十) 状态模式(State pattern) C++实现
- Head First 设计模式 C++实现-Strategy(策略模式)
- Head First 设计模式 C++实现-Strategy(策略模式)