懒汉模式写法
public class LazyMan {
private volatile static LazyMan lazyMan;
private LazyMan() {
System.out.println(Thread.currentThread().getName() + "线程名称");
}
public static LazyMan getInstance() {
if (null == lazyMan) {
synchronized (LazyMan.class) {
if (null == lazyMan) {
lazyMan = new LazyMan();
}
}
}
return lazyMan;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
LazyMan instance = LazyMan.getInstance();
}).start();
}
}
}
饿汉单例模式
public class HungryMan {
private static HungryMan hungryMan = new HungryMan();
private HungryMan (){
}
public static HungryMan getInstance(){
return hungryMan;
}
public static void main(String[] args) throws Exception {
HungryMan instance1 = HungryMan.getInstance();
Constructor<HungryMan> declaredConstructor = HungryMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
HungryMan instance2 = declaredConstructor.newInstance();
System.out.println("instance1 = " + instance1);
System.out.println("instance2 = " + instance2);
}
}
静态内部类
public class InnerSingle {
private InnerSingle (){
if (InnerHolder.innerSingle != null){
throw new RuntimeException("静态内部类不允许反射!!!");
}
}
public static class InnerHolder{
private static InnerSingle innerSingle = new InnerSingle();
}
public static InnerSingle getInstance(){
return InnerHolder.innerSingle;
}
public static void main(String[] args) throws Exception{
InnerSingle instance1 = InnerSingle.getInstance();
Constructor<InnerSingle> declaredConstructor = InnerSingle.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
InnerSingle instance2 = declaredConstructor.newInstance();
System.out.println("instance1 = " + instance1);
System.out.println("instance2 = " + instance2);
}
}
枚举单例
public enum SingleEnum {
INSTANCE;
public SingleEnum getInstance(){
return INSTANCE;
}
public static void main(String[] args) throws Exception {
Constructor<SingleEnum> declaredConstructor = SingleEnum.class.getDeclaredConstructor(String.class,int.class);
declaredConstructor.setAccessible(true);
SingleEnum singleEnum = declaredConstructor.newInstance();
System.out.println(singleEnum);
}
}