单例模式:确保一个类最多只有一个实例,并提供一个全局访问点.
public class Singleton {
private static Singleton uniqeInstance=null;
private Singleton(){
};
public static Singleton getInstance()
{
if(uniqeInstance==null)
{
uniqeInstance=new Singleton();
}
return uniqeInstance;
}
}
单例模式------多线程问题
双重检查加锁
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;
}
}