//懒汉式单例设计
package it.cast.threadtest;
public class LazyManSingleInstance {
private static LazyManSingleInstance instance = null; //如果添加了final,instance就会永远等于空
private LazyManSingleInstance(){ //不对外提供构造方法
}
public LazyManSingleInstance getInstance() {
if (instance == null) { //使用双层判断的形式,提高程序效率
synchronized (LazyManSingleInstance.class) {
if (instance == null) { //为空才创建
instance = new LazyManSingleInstance();
}
}
}
return instance;
}
}
因为好麻烦,所以一般都写饿汉式
package it.cast.threadtest;
public class HungerManSingleInstance {
private static final HungerManSingleInstance instance = new HungerManSingleInstance();
private HungerManSingleInstance() {
}
public HungerManSingleInstance getInstance() {
return instance;
}
}