单例模式写法

/**
 * 懒汉模式  懒加载思想  
 * 线程不安全 多线程下不能正常运行
 */
public class LhSingleton {

    private static LhSingleton instance;
    private LhSingleton(){ }

    public static LhSingleton getInstance(){
        if(instance==null){
            instance = new LhSingleton();
        }
        return instance;
    }
}

===========================================================================

/**
 * 懒汉模式 线程安全
 * 效率比较低
 */
public class LhSafeSingleton {
    private  static  LhSafeSingleton instance;
    private  LhSafeSingleton(){}

    public static  synchronized LhSafeSingleton getInstance(){
        if(instance==null){
            instance = new LhSafeSingleton();
        }
        return instance;
    }
}

===========================================================================

/**
 * 饿汉模式
 * 类加载的时候进行实例化
 */
public class EhSingle {
    private  static EhSingle instance = new EhSingle();
    private EhSingle (){}
    public static EhSingle getInstance(){
        return instance;
    }
}

===========================================================================

/**
 * 静态内部类
 * 实心懒加载思想
 * 只有显示通过调用getInstance方法时才会显示装载SingletonCreate类,
 * 从而实例化instance。想象一下,如果实例化instance很消耗资源,
 * 想让他延迟加载,另外一方面,在不希望在Singleton类加载时就实例化的情况下,
 * 不能确保Singleton类还可能在其他的地方被主动使用从而被加载,
 * 那么这个时候实例化instance显然是不合适的。
 */
public class StaticInnerSingleton {
    private StaticInnerSingleton(){}
    private  static class SingletonCreate{
        private static final StaticInnerSingleton instance = new StaticInnerSingleton();
    }
    public static final StaticInnerSingleton getInstance(){
        return SingletonCreate.instance;
    }
}

===========================================================================

/**
 * 双重检查锁定
 */
public class DoubleTestSingleton {
    private  volatile static DoubleTestSingleton instance;
    private  DoubleTestSingleton(){}
    public static  DoubleTestSingleton getInstance(){
        if(instance==null){
            synchronized (DoubleTestSingleton.class){
                if(instance ==null){
                    instance = new DoubleTestSingleton();
                }
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值