所谓类的单例设计模式,就是采取一定的方法保证整个软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)
单例模式的八种方式
饿汉式(静态常量)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
class Singleton01{ private Singleton01(){} private final static Singleton01 instance = new Singleton01() ; public static Singleton01 getInstance(){ return instance ; } }
|
饿汉式(静态代码块)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Singleton02{ private Singleton02(){} private final static Singleton02 instance ; static { instance = new Singleton02() ; } public static Singleton02 getInstance(){ return instance ; } }
|
懒汉式(线程不安全)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class Singleton03{ private static Singleton03 instance ; private Singleton03(){} public static Singleton03 getInstance(){ if (null == instance){ instance = new Singleton03(); } return instance ; } }
|
懒汉式(线程安全,同步方法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Singleton04{ private static Singleton04 instance ; private Singleton04(){} public static synchronized Singleton04 getInstance(){ if (null == instance){ instance = new Singleton04(); } return instance ; } }
|
#3# 懒汉式(线程安全,同步代码块)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Singleton05{ private static Singleton05 instance ; private Singleton05(){} public static Singleton05 getInstance(){ if (null == instance){ synchronized (Singleton05.class){ instance = new Singleton05(); } } return instance ; } }
|
双重检查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Singleton06{ private static Singleton06 instance ; private Singleton06(){} public static Singleton06 getInstance(){ if (null == instance){ synchronized (Singleton06.class){ if (null == instance){ instance = new Singleton06(); } } } return instance ; } }
|
静态内部类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class Singleton07{ private static Singleton07 instance ; private Singleton07(){}
private static class SingleInstance{ private static final Singleton07 SINGLETON_07 = new Singleton07(); } public static synchronized Singleton07 getInstance(){ return SingleInstance.SINGLETON_07 ; } }
|
枚举
1 2 3 4 5 6 7 8 9
|
enum Singleton08{ INSTANCE ; public void sayOK(){ System.out.println("ok ~ "); } }
|
细节说明
- 单例模式保证了系统内存中该类只存在一个对象,节省了系统资源,对于一些需要创建销毁的对象,使用单例模式可以提高系统性能
- 当想实例化一个单例类的时候,必须要记住使用响应的获取对象的方法,而不是使用new
- 单例模式使用的场景,需要频繁的进行创建和销毁的对象,创建对象耗时过多或耗费资源过多(即:重量级对象),但有经常用到的对象,工具类对象,频繁访问数据库或文件的对象(比如数据源,session工厂等)。