Java设计模式——单例模式

类的单例设计模式:采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法静态方法 。

①  

/*
 * 饿汉式1:静态变量
 */
class Singleton {
    private Singleton() {
    };
    
    private final static Singleton instance = new Singleton();
    
    public static Singleton getInstance() {
        return instance;
    }
}

 1 /*
 2  * 饿汉式2:静态代码块
 3  */
 4 class Singleton {
 5     private Singleton() {
 6     };
 7     
 8     private  static Singleton instance;
 9     static {
10         instance = new Singleton();
11     }
12     
13     public static Singleton getInstance() {
14         return instance;
15     }
16 }

 1 /*
 2  * 懒汉式1:线程不安全
 3  */
 4 class Singleton {
 5     private Singleton() {
 6     };
 7     
 8     private  static Singleton instance;
 9     
10     public static Singleton getInstance() {
11         if(instance == null){
12             instance = new Singleton();
13         }
14         return instance;
15     }
16 }

 1 /*
 2  * 懒汉式2:线程安全,并发小
 3  */
 4 class Singleton {
 5     private Singleton() {
 6     };
 7     
 8     private  static Singleton instance;
 9     
10     public static synchronized Singleton getInstance() {
11         if(instance == null){
12             instance = new Singleton();
13         }
14         return instance;
15     }
16 }

 1 /*
 2  * 双重校验:效率高,延迟加载,线程安全,
 3  */
 4 class Singleton {
 5     private Singleton() {
 6     };
 7     
 8     private static volatile Singleton instance;
 9     
10     public static Singleton getInstance() {
11         if (instance == null) {
12             synchronized (Singleton.class) {
13                 if (instance == null) {
14                     instance = new Singleton();
15                 }
16             }
17         }
18         return instance;
19     }
20 }

 1 /*
 2  * 静态内部类
 3  * 1.类加载时,静态内部类不加载,实现懒加载
 4  * 2.线程调用静态内部类时,JVM加载机制保证线程安全(类初始化,别的线程无法进入)
 5  */
 6 class Singleton {
 7     private Singleton() {
 8     };
 9     
10     private static class SingletonInstance {
11         private final static Singleton INSTANCE = new Singleton();
12     }
13     
14     public static Singleton getInstance() {
15         return SingletonInstance.INSTANCE;
16     }
17 }

1 /*
2  * 枚举类:借助jdk1.5枚举来实现单例模式
3  * 避免多线程同步问题,能防止反序列化重新创建新的对象
4  */
5 enum Singleton {
6     INSTANCE;
7 }

总结:

1)单例模式保证了系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能
2)当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用new
3)场景:需要频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多。如:重量级对象但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象;比如数据源、 sessionFactory等。

原文地址:https://www.cnblogs.com/gzhcsu/p/13255187.html