单例模式
1.饿汉式
package org.best.singleton;
public class HungerSingleton {
private HungerSingleton(){}
private static HungerSingleton hungerSingleton=new HungerSingleton();
public static HungerSingleton getHungerSingleton(){
return hungerSingleton;
}
}
2.懒汉式
package org.best.singleton;
public class LazySingleton {
private static boolean isFirst=true;
private LazySingleton(){
synchronized (LazySingleton.class){
if (isFirst){
isFirst=false;
}else {
throw new RuntimeException("不可重复创建");
}
}
}
private static volatile LazySingleton lazySingleton=null;
public LazySingleton getLazySingleton(){
if (lazySingleton==null){
synchronized (LazySingleton.class){
if (lazySingleton==null){
lazySingleton=new LazySingleton();
}
}
}
return lazySingleton;
}
}
3.静态内部类
package org.best.singleton;
import java.util.PrimitiveIterator;
public class InnerStaticSingleton {
private InnerStaticSingleton(){}
public static class getInnerStaticSingleton{
private static final InnerStaticSingleton SINGLETON=new InnerStaticSingleton();
}
private static InnerStaticSingleton getInstance(){
return getInnerStaticSingleton.SINGLETON;
}
}