美文网首页
单利模式

单利模式

作者: 康明 | 来源:发表于2017-01-04 21:35 被阅读0次

    1、懒汉式:

    //懒汉式

    public class Config {
    //3 声明类的静态变量
    private static Config cfg;
    //1 使用private修饰默认的构造方法
    private Config(){}
    //2 进行判断,如果对象存在,不再创建对象
    //4 为了保证线程同步,改为同步方法
    public synchronized static Config getInstance(){
    if(cfg == null){
    cfg = new Config();
    }
    return cfg;
    }
    }
    

    2、饿汉式

    //饿汉式

    public class Dog {
    private static Dog dog = new Dog();
    private Dog(){}//尽量写,防止自己创建对象而不是通过 单利创建;
    public static Dog getInstance(){
    return dog;
    }
    }
    

    相关文章

      网友评论

          本文标题:单利模式

          本文链接:https://www.haomeiwen.com/subject/nmjavttx.html