码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式:1-饿汉模式

时间:2017-09-09 18:17:18      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:on()   并且   one   get   hid   防止   lin   eager   1.5   

思想:

 

  饿汉模式是最常提及的2种单例模式之一,其核心思想,是类持有一个自身的 instance 属性,并且在申明的同时立即初始化。

  同时,类将自身的构造器权限设为 private,防止外部代码创建对象,对外只提供一个静态的 getInstance() 方法,作为获取单例的唯一入口。

 

技术分享
 1 public class EagerSingleton {
 2 
 3     private static final EagerSingleton instance = new EagerSingleton();
 4 
 5     private EagerSingleton() {
 6         
 7     }
 8 
 9     public static final EagerSingleton getInstance() {
10         return instance;
11     }
12 
13 }
饿汉模式

 

考虑反射:

 

  在构造器中,增加对 instance 的空判断,可以有效地阻止反射入侵。

 

考虑多线程:

 

  饿汉模式由于在申明的同时立即初始化,所以即使在并发的情况下,仍然可以保证单例。

 

技术分享
 1 public final class EagerSingleton {
 2 
 3     private static final EagerSingleton instance = new EagerSingleton();
 4 
 5     private EagerSingleton() {
 6         if (instance != null) {
 7             throw new IllegalStateException();
 8         }
 9     }
10 
11     public static final EagerSingleton getInstance() {
12         return instance;
13     }
14 
15 }
完整的饿汉模式

 

单例模式:1-饿汉模式

标签:on()   并且   one   get   hid   防止   lin   eager   1.5   

原文地址:http://www.cnblogs.com/jing-an-feng-shao/p/7498750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!