您的位置:首页 > 其它

单件模式

2012-08-14 11:13 260 查看
在有的程序中某些类只能有一个实例,比如说线程池管理,注册表等等。

实现上通常采取将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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: