本文共 10673 字,大约阅读时间需要 35 分钟。
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例。
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
主要解决:一个全局使用的类频繁地创建与销毁。
何时使用:当您想控制实例数目,节省系统资源的时候。
如何解决:判断系统是否已经有这个单例,如果有则返回,如果没有则创建。
关键代码:构造函数是私有的。
缺点:没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化。
注意事项:getInstance() 方法中需要使用同步锁 synchronized (Singleton.class) 防止多线程同时进入造成 instance 被多次实例化。
所谓类的单例设计模式(Singleton Pattern),就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。
这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。比如 Hibernate 的 SessionFactory,它充当数据存储源的代理,并负责创建 Session 对象。SessionFactory 并不是轻量级的,一般情况下,一个项目通常只需要一个 SessionFactory 就够,这是就会使用到单例模式。
类图:
角色分析:
getInstance()
类方法来供外界使用。一个类只有一个对象实例,即 单例模式。可以类比孤独的乔治。
孤独的乔治,是一只加拉帕戈斯象龟平塔岛象龟亚种个体。自1971年被发现到2012年确认死亡为止,被认为是平塔岛象龟中已知的最后一个个体。它被认为是世界上最稀有的动物,也是加拉帕戈斯群岛乃至全球物种保护的象征之一。单例模式有八种方式:
饿汉式(静态常量)(推荐使用)
饿汉:类加载的时候,把对象也创建出来了,很容易浪费空间,因为不知道什么时候类就加载了,而对象如果不用,就造成了空间浪费。
饿汉式(静态代码块)(推荐使用)
比起静态常量来说,静态代码块中可以写很多判断筛选信息。
懒汉式(线程不安全)
懒汉:用的时候才去创建
懒汉式(线程安全,同步代码块)
枚举(推荐使用)
饿汉式(静态常量)应用实例步骤如下:
getInstance()
代码演示:
package com.nemo.singleton.type1;public class SingletonTest01 { public static void main(String[] args) { //测试 Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); }}//饿汉式(静态变量)class Singleton { //1. 构造器私有化, 外部不能 new private Singleton() {} //2.本类内部创建对象实例 private final static Singleton instance = new Singleton(); //3. 提供一个公有的静态方法,返回实例对象 public static Singleton getInstance() { return instance; }}
优缺点说明:
代码演示:
package com.nemo.singleton.type2;public class SingletonTest02 { public static void main(String[] args) { //测试 Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); }}//饿汉式(静态变量) class Singleton { //1. 构造器私有化, 外部不能 new private Singleton() {} //2.本类内部创建对象实例 private static Singleton instance; static { // 在静态代码块中,创建单例对象(类装载的时候执行) instance = new Singleton(); } //3. 提供一个公有的静态方法,返回实例对象 public static Singleton getInstance() { return instance; }}
优缺点说明:
代码演示:
package com.nemo.singleton.type3;public class SingletonTest03 { public static void main(String[] args) { System.out.println("懒汉式 1 , 线程不安全~"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); }}class Singleton { private static Singleton instance; private Singleton() {} //提供一个静态的公有方法,当使用到该方法时,才去创建 instance //即 懒汉式 public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; }}
优缺点说明:
if (singleton == null)
判断语句块,还未来得及往下执行(还未构造对象),另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式。代码演示:
package com.nemo.singleton.type4;public class SingletonTest04 { public static void main(String[] args) { System.out.println("懒汉式 2 , 线程安全~"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); }}// 懒汉式(线程安全,同步方法)class Singleton { private static Singleton instance; private Singleton() {} //提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题 //即懒汉式 public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; }}
优缺点说明:
getInstance()
方法都要进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接 return 就行了。方法进行同步效率太低。代码演示:
class Singleton { private static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if(singleton == null) { synchronized(Singleton.class) { singleton = new Singleton(); } } return singleton; }}
优缺点说明:
if (singleton == null)
判断语句块,还未来得及往下执行(还未构造对象),另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式。代码演示:
package com.nemo.singleton.type6;public class SingletonTest06 { public static void main(String[] args) { System.out.println("双重检查"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); }}// 懒汉式(线程安全,同步方法)class Singleton { private static volatile Singleton instance; private Singleton() {} //提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题 //同时保证了效率, 推荐使用 public static Singleton getInstance() { //第一次检查,可以保证在对象创建好之后,每个线程在想获得类的实例不需要再进行同步 //解决了“懒汉式(线程安全,同步方法)”的缺点 if(instance == null) { synchronized (Singleton.class) { //第二次检查,可以避免当多个线程挤进此语句时,创建多个实例 //解决了“懒汉式(线程不安全)”的缺点 if(instance == null) { instance = new Singleton(); } } } return instance; }}
volatile:轻量级的 synchronized,只能修饰变量。让修改值立即更新到主存,多线程情况下防止指令重排序。能保证此对象的同步创建,类似于原子性创建,不能被中断,一次顺序执行到底。由于 new 不是原子方法,所以执行当中有很多个步骤,可能被多线程插队,导致创建错误,所以加入 volatile 保证同步创建,原子创建。
防止在 new 实例的时候,还没初始化完,有其他线程进来,实例此时已经不为空,多线程拿到的实例数据就不一致,加了该关键字后,先初始化完成后再赋值给实例,即 轻量级同步。精确地说就是,编译器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存器里的备份。
优缺点说明:
if (singleton == null)
检查,这样就可以保证线程安全了。if (singleton == null)
,直接 return 实例化对象,也避免的反复进行方法同步。其实,大家也可以想想为什么要双重检查?如果直接加同步锁单重检查会怎么样?
如果直接加同步锁单重检查,会极大的影响效率,毕竟这就相当于单线程了,每个多线程都得在这里卡住,只有一个能通过。如果是双重检查就不一样了,我们第一重最外层检查可以不加锁,管的松一点,第一重管这么松都不满足条件没过去,那第二重就不必说了,所以第一重可以帮我们筛选掉绝大部分线程,且不影响效率,毕竟没有加同步锁;而为了安全,我们第二重就要严一点,一个错误都不能放过,但是能通过第一重到达第二重的线程毕竟是少数,所以第二重严一点也不会影响效率。其实这可以类比一下hashcode() 和 equals()
hashCode()方法和equals()方法的作用其实是一样的,在Java里都是用来对比两个对象是否相等一致。那么equals()既然已经能实现对比的功能了,为什么还要hashCode()呢?因为重写的equals()里一般比较的比较全面比较复杂,这样效率就比较低,而利用hashCode()进行对比,则只要生成一个hash值进行比较就可以了,效率很高。那么hashCode()既然效率这么高为什么还要equals()呢? 因为hashCode()并不是完全可靠,有时候不同的对象他们生成的hashcode也会一样(生成hash值得公式可能存在的问题),所以hashCode()只能说是大部分时候可靠,并不是绝对可靠,所以我们可以得出:1.equals()相等的两个对象他们的hashCode()肯定相等,也就是用equals()对比是绝对可靠的。2.hashCode()相等的两个对象他们的equal()不一定相等,也就是hashCode()不是绝对可靠的。所有对于需要大量并且快速的对比的话如果都用equals()去做显然效率太低,所以解决方式是,每当需要对比的时候,首先用hashCode()去对比,如果hashCode()不一样,则表示这两个对象肯定不相等(也就是不必再用equal()去再对比了),如果hashCode()相同,此时再对比他们的equals(),如果equals()也相同,则表示这两个对象是真的相同了,这样既能大大提高了效率也保证了对比的绝对正确性!
代码演示:
package com.nemo.singleton.type7;public class SingletonTest07 { public static void main(String[] args) { System.out.println("使用静态内部类完成单例模式"); Singleton instance = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance == instance2); // true System.out.println("instance.hashCode=" + instance.hashCode()); System.out.println("instance2.hashCode=" + instance2.hashCode()); }}// 静态内部类完成,推荐使用class Singleton { private static volatile Singleton instance; //构造器私有化 private Singleton() {} //写一个静态内部类,该类中有一个静态属性 Singleton private static class SingletonInstance { private static final Singleton INSTANCE = new Singleton(); } //提供一个静态的公有方法,直接返回 SingletonInstance.INSTANCE public static synchronized Singleton getInstance() { return SingletonInstance.INSTANCE; }}
类中套类,既保证了不会装载浪费空间,又保证了用的时候单一且线程安全。上来就创一个,可以避免多线程问题。
在类装载的时候,静态内部类不会装载。当调用的时候,静态内部类才会被装载,当类装载的时候线程是安全的。优缺点说明:
代码演示:
package com.nemo.singleton.type8;public class SingletonTest08 { public static void main(String[] args) { Singleton instance = Singleton.INSTANCE; Singleton instance2 = Singleton.INSTANCE; System.out.println(instance == instance2); System.out.println(instance.hashCode()); System.out.println(instance2.hashCode()); instance.sayOK(); }}//使用枚举,可以实现单例, 推荐enum Singleton { INSTANCE; //属性 public void sayOK() { System.out.println("ok~"); }}
优缺点说明:
问:
静态方法可以通过类来调用,其余得创建对象来调用。那单例模式与一个类全是静态方法在设计角度的差别是什么呢?
答:
因为单例模式可以充分的使用面向对象的封装,继承,多态;而一个类所有静态方法不行,在设计角度远不如单态设计灵活。 转载地址:http://odtkz.baihongyu.com/