java设计模式(三)

单例模式
在一个jvm中有且仅有一个对象
(1)内部静态类实现

 class Singleton{
    /*构造方法私有 防止实例化*/
    private Singleton(){};

    public static Singleton getInstance(){
        SingletonFactory.instance;
    }

    public static class SingletonFactory{
        private static Singleton instance = new Singleton();
    }

    private Object readObject(){
        return getInstance;
    }
   }

(2)synchronized

 class Singleton{
    private Singleton instance = null;

        /*构造方法私有 防止实例化*/
    private Singleton(){};

    public Singleton getInstance(){
        if(instance==null)syncInst();
        return instance;
    }

    private static synchronized void syncInst(){
        if(singleton==null){
        singleton = new Singleton1();
        }
    }


   }
原文地址:https://www.cnblogs.com/b-dong/p/6061452.html