单例模式
单例模式
重要思想:构造器私有,保证内存中只有一个对象
饿汉式
public class Hungry {
    private Hungry(){
    }
    private final static Hungry HUNGRY = new Hungry();
    public static Hungry getInstance(){
        return HUNGRY;
    }
    
}
懒汉式
public class LazyMan {
    private LazyMan(){}
    private volatile static LazyMan lazyMan;
    //双重检测锁模式
    public static LazyMan getInstance(){
        if (lazyMan==null){
            synchronized (LazyMan.class){
                if (lazyMan == null){
                    LazyMan lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }
}
public class LazyMan {
    private LazyMan(){
        synchronized (LazyMan.class){
            if (lazyMan!=null){
                throw new RuntimeException("禁止反射");
            }
        }
        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static LazyMan lazyMan;
    //双重检测锁模式
    public static LazyMan getInstance(){
        if (lazyMan==null){
            synchronized (LazyMan.class){
                if (lazyMan == null){
                    lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }
    public static void main(String[] args) throws Exception {
        LazyMan instance = LazyMan.getInstance();
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        constructor.setAccessible(true);
        LazyMan instance1 = constructor.newInstance();
        System.out.println(instance);
        System.out.println(instance1);
    }
}
public class LazyMan{
    public LazyMan(){
        
    }
    private volatile static LazyMan lazyMan;
    public static LazyMan getInstanace(){
        if(lazyMan==null){
            synchronized(Lazyman.class){
                if(lazyMan==null){
                    lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }
}
静态内部类式
public class Holder {
    private Holder(){
        
    }
    public static Holder getInstance(){
        return InnerClass.HOLDER;
    }
    public static class InnerClass{
        private static final Holder HOLDER = new Holder();
    }
}
枚举
public enum EnumSingle {
    INSTANCE;
    public static EnumSingle getInstance(){
        return INSTANCE;
    }
}
class Test{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        EnumSingle instance = EnumSingle.INSTANCE;
        Constructor<EnumSingle> constructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
        constructor.setAccessible(true);
        EnumSingle instance2 = constructor.newInstance();
        System.out.println(instance);
        System.out.println(instance2);
    }
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号