单例模式

单例模式通常有两种表现形式:懒汉式单例和饿汉式单例。

1.懒汉式单例:该模式特点是类在加载的过程的时候没有生成一个单例、只有当调用的时候才去创建这个单例。

复制代码
 1 public class LazySingleton
 2 {
 3     private static volatile LazySingleton instance=null;    //保证 instance 在所有线程中同步
 4     private LazySingleton(){}    //private 避免类在外部被实例化
 5     public static synchronized LazySingleton getInstance()
 6     {
 7         //getInstance 方法前加同步
 8         if(instance==null)
 9         {
10             instance=new LazySingleton();
11         }
12         return instance;
13     }
14 }
复制代码

2.饿汉式单例:该模式的特点是类一旦加载就创建一个单例,保证在调用 getInstance 方法之前单例已经存在了。

复制代码
1 public class HungrySingleton
2 {
3     private static final HungrySingleton instance=new HungrySingleton();
4     private HungrySingleton(){}
5     public static HungrySingleton getInstance()
6     {
7         return instance;
8     }
9 }
复制代码
posted on 2019-04-19 09:16  Eminem。  阅读(111)  评论(0编辑  收藏  举报