设计模式之单例设计模式

217 阅读1分钟

定义

  • 单例模式是创建型设计模式,其思想是私有化对象的构造方法,对外只提供一个可获取对象实例的方法

代码实践

  • 饿汉式
/**
 * 单例模式实例
 *
 * @Author: ZRH
 * @Date: 2021/2/7 10:05
 */
public class SingletonTest {

    private final static SingletonTest singletonTest = new SingletonTest();

    /**
     * 构造方法私有化,不能外部创建改对象
     */
    private SingletonTest() {
    }

    public static SingletonTest getSingletonTest() {
        return singletonTest;
    }
}
  • 懒汉式
/**
 * 单例模式实例
 *
 * @Author: ZRH
 * @Date: 2021/2/7 10:05
 */
public class SingletonTest {

    private final static SingletonTest singletonTest;

    /**
     * 构造方法私有化,不能外部创建改对象
     */
    private SingletonTest() {
    }

    public static SingletonTest getSingletonTest() {
        if (null == singletonTest) {
            singletonTest = new SingletonTest();
        }
        return singletonTest;
    }
}
  • 双重检验线程安全式
/**
 * 单例模式实例
 *
 * @Author: ZRH
 * @Date: 2021/2/7 10:05
 */
public class SingletonTest {

    private volatile static SingletonTest singletonTest;

    /**
     * 构造方法私有化,不能外部创建改对象
     */
    private SingletonTest() {
    }

    public static SingletonTest getSingletonTest() {
        if (null == singletonTest) {
            synchronized (SingletonTest.class) {
                if (null == singletonTest) {
                    singletonTest = new SingletonTest();
                }
            }
        }
        return singletonTest;
    }
}
  • 静态内部类创建实例,利用类加载器的线程安全特性保证了单例对象的初始化线程安全。静态内部类只在使用的时间才会被加载一次,是延迟初始化加载。
/**
 * 单例模式
 *
 * @Author: ZRH
 * @Date: 2021/1/26 18:02
 */
public class SingletonTest {

    private static class TestHolder {
        static final SingletonTest singletonTest = new SingletonTest();
    }

    /**
     * 构造方法私有化,不能外部创建改对象
     */
    private SingletonTest() {
    }
    
    public static SingletonTest getInstance() {
        return TestHolder.singletonTest;
    }

}

更多单例模式详解请点击

  • 最后虚心学习,共同进步 -_-