单例模式5种实现方法

俄汉式(不能懒加载)

/**
 * 优点:线程安全,调用效率较高
 * 缺点:不能懒加载
 */
public class Sinleton {

    //1.私有化构造器
    private Sinleton() {
    }
    //2.立即加载对象
    private static Sinleton instance = new Sinleton();

    //3.提供访问接口
    public static Sinleton getInstance(){
        return instance;
    }

}


懒汉式(可以懒加载 )

/**
 * 优点:懒加载,避免了资源浪费
 * 缺点:通过synchronized实现同步,并发效率低
 */
public class Sinleton {

    //1.私有化构造器
    private Sinleton() {
    }
    private static Sinleton instance = null;

    //2.提供访问接口
    public synchronized static Sinleton getInstance(){   //synchronized同步
        if(instance==null)                     //3.第一次调用时候加载实例对象
            instance = new Sinleton();
        return instance;
    }

}


内部类法(可以懒加载)

public class SingletonDemo1 {

    private static class InnerClass{
        public static SingletonDemo1 instance = new SingletonDemo1();
    }

    public static SingletonDemo1 get(){
        return InnerClass.instance;
    }

}

枚举类法

public enum SingletonDemo2 {

    INSTANCE;

}

双重检测锁法(可以懒加载,由于jvm指令重排机制,故不建议使用)

public class SingletonDemo {

    //私有构造方法
    private SingletonDemo() {
    }

    private static SingletonDemo instance;

    public static SingletonDemo get(){
        SingletonDemo s;
        if(instance==null){

            synchronized (SingletonDemo.class){
                s = instance;
                if(s==null){
                    synchronized (SingletonDemo.class){
                        s = new SingletonDemo();
                    }
                    instance = s;
                }

            }

        }

        return instance;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值