单例-设计模式(Design Pattern)
- 设计模式基础知识
- 基础概念
. . . .简而言之,就是套路二字.是一套反复被使用,多数人知晓的,经过分类编目,代码设计经验的总结.对待不同情况,可以使用的最优解.还是古人云的好啊 .
. . . .自古深情留不住,唯有套路得人心! - 作用
. . . . 实用设计模式不仅仅可以提高代码重用度,代码更容易理解,保证代码的可靠性. - 使用场景
. . . . 工具类,配置文件,线程池,缓存,日志等
- 基础概念
- 单例设计模式—饿汉式
- 代码参考
public class Singleton { //1.将构造方法私有化,不允许外部直接创建对象 private Singleton() { } //2.创建类的唯一实例 ,其实只用加一个static即可,对象只会有一个了.静态修饰符修饰的变量只会随着类的加载而加载.类只回加载一次. private static Singleton instance = new Singleton(); //3.提供一个用于获取实例的方法 public static Singleton getInstance(){ // do filter return instance; } }
- 单例设计模式—懒汉式
- 代码参考
public class SingletonLazy { //1.将构造方法私有化,不允许外部直接创建对象 private SingletonLazy() { } //2.类变量会随着类的加载而初始化为null,用到的时候再new 对象,并将对象地址赋值给私有静态变量. private static SingletonLazy instance; //3.提供一个用于获取实例的方法 public static SingletonLazy getInstance(){ // do filter if(instance == null){ instance = new SingletonLazy(); } return instance; } }
- 单例设计模式—测试
- 代码参考
public class SingletonTest { // 比对对象地址是否相等 public static void main(String[] args) { Singleton s0 = Singleton.getInstance(); Singleton s1 = Singleton.getInstance(); System.out.println(s0); System.out.println(s1); System.out.println("-------------------------"); SingletonLazy s2 = SingletonLazy.getInstance(); SingletonLazy s3 = SingletonLazy.getInstance(); System.out.println(s2); System.out.println(s3); } }
- 单例设计模式—总结
- 饿汉式,是加载类时比较慢,但运行时获取的对象速度比较快,线程安全.
- 懒汉式加载类时比较快,但运行获取对象的速度比较慢,线程不安全