单列模式

实现单例模式思路:

    一个类能返回对象一个引用(永远是同一个)和一个获得该实例的方法(必须是静态方法,通常使用getInst
 ance 这个名称);当我们调用这个方法时,如果类持有的引用不为空就返回这个引用,如果类保持的引用为空
 就创建 该类的实例并将实例的引用赋予该类保持的引用;同时我们还将该类的构造函数定义为私有方法,这样
 其他处的 代码就无法通过调用该类的构造函数来实例化该类的对象,只有通过该类提供的静态方法来得到该类
 的唯一实例

总结一下要点:

  1. 只能拥有一个对象。
  2. 构造函数私有 以保证不能创建多余的对象。
  3. 在类内创建一个对象,将其引用作为成员变量,但构造函数是 私有的,无法new对象,只能将类内对象的引用加上static 修饰符,以保证可以直接用类加载调用。
  4. 这个对象作为成员变量,一般为private,所以有对应的get 方法。
  5. getInstance() 方法必须为静态方法。

----饿汉式-----

class Singleton {
    private Singleton() {}
    private static final Singleton singleton = new Singleton();
    public static Singleton getInstance() {
        return singleton;
    }
}

------懒汉式 (延迟加载)-------

1 . 线程不安全写法,多线程时可能会同时new 对象



class Singleton {
    private Singleton() {}
    private static Singleton singleton = null;
    public static Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

2 . 线程安全写法,但效率太低,一般不用

class Singleton {
    private Singleton() {}
    private static Singleton singleton = null;
    public static synchronized Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

--------- 双重校验锁,较常用,解决了线程问题和效率问题-----------

class Singleton {
    private Singleton() {}
    private static Singleton singleton = null;
    public static Singleton getInstance(){
        if(singleton == null){
            synchronized(Singleton.class) {
                if(singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

---------- 静态内部类 ,好像也比较常用-----------

class Singleton {
    private Singleton() {
        System.out.println("singleton create");
    }
    private static class InstanceHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return InstanceHolder.INSTANCE;
    }
}

----------枚举----------

public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  
    }  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值