JAVA设计模式-单例模式

一、懒汉模式

public class LazySingleton {

    private volatile static LazySingleton  instance=null;
    //私有构造方法
    private LazySingleton(){
    };
    //提供全局访问接口
    public static LazySingleton getInstance(){
        if (instance==null){
            synchronized (LazySingleton.class){
                if (instance==null){
                    instance=new LazySingleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        new Thread(()->{
            LazySingleton lazySingleton=LazySingleton.getInstance();
            System.out.println(lazySingleton);
        }).start();
        new Thread(()->{
            LazySingleton lazySingleton=LazySingleton.getInstance();
            System.out.println(lazySingleton);
        }).start();
    }

}

二、饿汉模式

public class HungrySingleton {

    private volatile static HungrySingleton  instance=new HungrySingleton();
    private HungrySingleton(){

    }
    public static HungrySingleton getInstance(){
        return instance;
    }


    public static void main(String[] args) {
        new Thread(()->{
            HungrySingleton hungrySingleton=HungrySingleton.getInstance();
            System.out.println(hungrySingleton);
        }).start();
        new Thread(()->{
            HungrySingleton hungrySingleton=HungrySingleton.getInstance();
            System.out.println(hungrySingleton);
        }).start();
    }

}

三、静态内部类

class InnerClassSingleton {
    private static class InnerClassHolder{
        private volatile static InnerClassSingleton instance=new InnerClassSingleton();
    }
    private InnerClassSingleton(){

    }
    public static InnerClassSingleton getInstance(){
        return InnerClassHolder.instance;
    }

    public static void main(String[] args) {
        new Thread(()->{
            InnerClassSingleton innerClassSingleton=InnerClassSingleton.getInstance();
            System.out.println(innerClassSingleton);
        }).start();
        new Thread(()->{
            InnerClassSingleton innerClassSingleton=InnerClassSingleton.getInstance();
            System.out.println(innerClassSingleton);
        }).start();
    }
}

 

你可能感兴趣的:(java,java,设计模式)