Chinaunix首页 | 论坛 | 博客
  • 博客访问: 428400
  • 博文数量: 54
  • 博客积分: 610
  • 博客等级: 上士
  • 技术积分: 721
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-24 10:52
文章分类

全部博文(54)

文章存档

2013年(27)

2012年(11)

2011年(16)

分类: Java

2013-08-01 22:56:08

 单例模式很简单,同时应用范围也很广泛。
什么意思呢?就是说,某个类只能有一个实例。
这里我举个例子,God 对于某个宗教,他们的真神只有一个。
下面看代码

God

点击(此处)折叠或打开

  1. package designPattern.singleton;

  2. public class God {

  3.     /**
  4.      * @param args
  5.      */
  6.     private static God trueGod;

  7.     private God(){
  8.         //nothing, we can't trust in more than two gods
  9.         //注意构造函数为私有,这样在这个类外,就不能调用new God();
  10.     }
  11.     
  12.     public static God getInstance(){
  13.         if(trueGod == null){
  14.             trueGod = new God();
  15.         }
  16.         return trueGod;
  17.     }
  18.     public void getInfo(){
  19.         System.out.println("I'm the God :"+trueGod.toString());
  20.     }

  21. }
然后是信仰者的类
Believer

点击(此处)折叠或打开

  1. package designPattern.singleton;

  2. public class Believer {

  3.     /**
  4.      * @param args
  5.      */
  6.     public static void main(String[] args) {
  7.         // TODO Auto-generated method stub
  8.         //three gods, but all the same one
  9.         God god1 = God.getInstance();
  10.         god1.getInfo();
  11.         
  12.         
  13.         God god2 = God.getInstance();
  14.         god2.getInfo();
  15.         
  16.         God god3 = God.getInstance();
  17.         god3.getInfo();

  18.     }

  19. }
结果

  1. I'm the God :designPattern.singleton.God@1dd61ee4
  2. I'm the God :designPattern.singleton.God@1dd61ee4
  3. I
看,三个真神,其实都是一个,输出了引用的地址。
 单例模式很简单,就是在构造函数中多了加一个构造函数,访问权限是private 的就可以了,这个模
式是简单,但是简单中透着风险,风险?什么风险?在一个B/S 项目中,每个HTTP Request 请求到J2EE
的容器上后都创建了一个线程,每个线程都要创建同一个单例对象,怎么办?

  1.    if(trueGod == null){
  2.             trueGod = new God();
  3.         }

在这段代码中,,假如现在有两个线程A 和线程B,线程A 执行到 trueGod = new God();,正在申请内存分配,可能需要0.001 微秒,就在这0.001 微秒之内,线程B 执
行到 if(trueGod == null),你说这个时候这个判断条件是true 还是false?是true,那然后呢?线程B 也往下走,于是乎就在内存中就有两个SingletonPattern 的实例了。
一个简单的解决方法:
通用代码

点击(此处)折叠或打开

  1. public class SingletonPattern {
  2. private static final SingletonPattern singletonPattern= new
  3. SingletonPattern();

  4. private SingletonPattern(){
  5. }
  6. public synchronized static SingletonPattern getInstance(){
  7. return singletonPattern;
  8. }
  9. }



阅读(1995) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

blue_11102013-08-01 23:00:30

Java反射机制是能够实例化构造方法为private的类