01 单例模式

   代码地址: https://gitee.com/powerCheng/learn_designmode.git 

  • 饿汉模式

/**
 * 单例的饿汉模式
 *
 * @author chengwei
 * @date 2019-06-06 10:01
 */
public class Singleton {
    /** 当加载Singleton.class时创建该对象 */
    private static Singleton singleton = new Singleton();

    /** 注意将构造器改为私有的 */
    private Singleton() {
    }

    public static Singleton getInstance() {
        return singleton;
    }
}
  • 懒汉模式

案例1:

/**
 * 单例线程安全的懒汉模式
 *
 * @author chengwei
 * @date 2019-06-06 10:04
 */
public class Singleton {
    /** 私有的 */
    private volatile static Singleton singleton;

    /** 私有的 */
    private Singleton() {
    }

    private static Singleton getInstance() {
        if (null == singleton) {
            synchronized (Singleton.class) {
                // 获取锁后再判断下是否为null, 有可能在等待锁的时候上一个线程已经创建了对象
                if(null == singleton){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

案例2:

/**
 * 单例线程安全的懒汉模式
 *
 * @author chengwei
 * @date 2019-06-06 10:08
 */
public class Singleton {

    /** 私有的 */
    private Singleton() {
    }

    /** 私有的静态内部类 */
    private static class SingletonFactory {
        private static Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        // 根据JVM加载机制, 第一次使用某个类的时候才会去加载这个类.
        // 所以只有当调用getInstance()方法时类SingletonFactory才会被加载, 同时instance对象将会被创建
        return SingletonFactory.instance;
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值