单件模式
2012-08-14 11:13
260 查看
在有的程序中某些类只能有一个实例,比如说线程池管理,注册表等等。
实现上通常采取将Sigleton的构造函数设置为私有,然后public一个getInstance函数,在该函数里面判断是否已经实例化该单件,若没有,则实例化,否则返回已经实例的对象。
c++代码中没有提供可跨平台的加锁方法,先附上java代码,慢慢寻求c++的实现。如果不需要实现多线程版本,c++实现也是很简单
多线程版本的getInstance应该为:
实现上通常采取将Sigleton的构造函数设置为私有,然后public一个getInstance函数,在该函数里面判断是否已经实例化该单件,若没有,则实例化,否则返回已经实例的对象。
c++代码中没有提供可跨平台的加锁方法,先附上java代码,慢慢寻求c++的实现。如果不需要实现多线程版本,c++实现也是很简单
package headfirst.singleton.chocolate; public class ChocolateBoiler { private boolean empty; private boolean boiled; private static ChocolateBoiler uniqueInstance; private ChocolateBoiler() { empty = true; boiled = false; } public static ChocolateBoiler getInstance() { if (uniqueInstance == null) { System.out.println("Creating unique instance of Chocolate Boiler"); uniqueInstance = new ChocolateBoiler(); } System.out.println("Returning instance of Chocolate Boiler"); return uniqueInstance; } public void fill() { if (isEmpty()) { empty = false; boiled = false; // fill the boiler with a milk/chocolate mixture } } public void drain() { if (!isEmpty() && isBoiled()) { // drain the boiled milk and chocolate empty = true; } } public void boil() { if (!isEmpty() && !isBoiled()) { // bring the contents to a boil boiled = true; } } public boolean isEmpty() { return empty; } public boolean isBoiled() { return boiled; } } public class ChocolateController { public static void main(String args[]) { ChocolateBoiler boiler = ChocolateBoiler.getInstance(); boiler.fill(); boiler.boil(); boiler.drain(); // will return the existing instance ChocolateBoiler boiler2 = ChocolateBoiler.getInstance(); } }
多线程版本的getInstance应该为:
public class Singleton { private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
相关文章推荐
- .net 单件模式(基类)
- 设计模式学习笔记(二)——Singleton单件模式
- 单件模式Singleton Pattern
- 【读书笔记】HeadFirst设计模式——单件不简单:详述实现Singleton模式需要考虑的方方面面
- 可继承的模板类单件模式
- .NET设计模式(2):单件模式(Singleton Pattern)
- 单件模式之土著人地可乐瓶
- 单件模式(Singleton)
- 设计模式——单件模式
- 设计模式初学者系列-单件模式
- 单件模式(Singleton Pattern)
- 从实例重温工厂模式和单件模式
- 单件模式(Singleton Pattern)
- 单件模式(Singleton Pattern)
- 系统架构技能之设计模式-单件模式 推荐
- 单件(单态,Singleton)模式部分
- 使用工厂模式和单件模式构建通用数据库访问类
- 单件模式
- 设计模式---单件(C++版) 希望大家顶一下
- 设计模式---单件(C++版) 比较通用的单件模式(STL实现)