单例设计模式

饿汉式:

 1 public class Singleton {
 2     // 直接创建对象
 3     public static Singleton instance = new Singleton();
 4 
 5     // 私有化构造函数
 6     private Singleton() {
 7     }
 8 
 9     // 返回对象实例
10     public static Singleton getInstance() {
11         return instance;
12     }
13 }

懒汉式:

 1 public class Singleton {
 2     // 声明变量
 3     private static volatile Singleton singleton = null;
 4 
 5     // 私有构造函数
 6     private Singleton() {
 7     }
 8 
 9     // 提供对外方法
10     public static Singleton getInstance() {
11         if (singleton == null) {
12             synchronized (Singleton.class) {
13                 if (singleton == null) {
14                     singleton = new Singleton();
15                 }
16             }
17         }
18         return singleton;
19     }
20 
21 }
原文地址:https://www.cnblogs.com/ffeiyang/p/9542329.html