单例模式
2016-02-22 15:03
337 查看
单例模式:
确保一个类只有一个实例,并提供一个全局访问点。
单例模式类图:
经典单例模式实现:
上面的经典单例模式存在多线程安全问题,解决方法参考面试题2:实现单例模式(offer)
确保一个类只有一个实例,并提供一个全局访问点。
单例模式类图:
经典单例模式实现:
class Singleton{ private: static Singleton *uniqueInstance; Singleton(){} public: static Singleton *getInstance(){ if (uniqueInstance == NULL) uniqueInstance = new Singleton(); return uniqueInstance; } };下面来看如何将一个普通的巧克力工厂类转为单例类:
class ChocolateBoiler{ private: bool empty; bool boiled; public: ChocolateBoiler(){//这是原来的构造函数 empty = true; boiled = false; } 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; } };改成单例类后如下:
class ChocolateBoiler{ private: static ChocolateBoiler *uniqueInstance; //* bool empty; bool boiled; ChocolateBoiler(){//*这是新的构造函数 empty = true; boiled = false; } public: static ChocolateBoiler *getInstance(){//* if (uniqueInstance == NULL) uniqueInstance = new ChocolateBoiler(); 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; } };
上面的经典单例模式存在多线程安全问题,解决方法参考面试题2:实现单例模式(offer)
相关文章推荐
- svm小结
- MBProgressHUD
- 一个帖子学会Android开发四大组件
- Xcode7免证书进行真机调试
- 处理大量配置信息的一种方法
- php empty()与isset()
- iOS中登录的遮盖SVProgressHUD
- js事件代理
- windows服务
- (引文)可扩展的分布式数据库架构
- DecorView
- 支付宝sdk的使用及常见问题
- 保持顺序的 Java Properties 类
- 常用系统广播
- APP打包党的生意经:加入恶意程序 一月净赚150万
- Redis (1) —— 安装
- mallinfo, 打印堆栈, malloc钩子, mtrace()
- Android上传文件到服务器
- ThinkPHP3.2.3的URL重写时遇到No input file specified的解决方法,htaccess规则问题
- 学习 Spring-Cloud - 写一个微服务