单例模式

来源:互联网 发布:锐战网络 编辑:程序博客网 时间:2024/06/01 12:45

应用场景 :线程池 、数据库 连接池  缓存 硬件设备等  

如果有多个实例 会有造成冲突   导致 结果不一致性等问题


public class Singleton {

private static Singleton uniqeInstance=null;

private Singleton(){

};

public static Singleton getInstance()
{
if(uniqeInstance==null)
{
uniqeInstance=new Singleton();
}
return uniqeInstance;

}


}

单例模式的优化

多线程优化 加入同步锁

2 双重锁检查


public class ChocolateFactory {


private boolean empty;
private boolean boiled;
public volatile static ChocolateFactory uniqueInstance = null;


private ChocolateFactory() {
empty = true;
boiled = false;
}


public static ChocolateFactory getInstance() {


if (uniqueInstance == null) {
synchronized (ChocolateFactory.class) {
if (uniqueInstance == null) {
uniqueInstance = new ChocolateFactory();
}
}
}


return uniqueInstance;


}

3 急切创建

public class Singleton {

private static Singleton uniqeInstance= new  Singleton ()  ;

private Singleton(){

};

public static Singleton getInstance()
{
if(uniqeInstance==null)
{
uniqeInstance=new Singleton();
}
return uniqeInstance;

}


原创粉丝点击