代码地址: 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;
}
}