1、单例模式是“对象池模式”的一种特殊情况

2、单例模式要解决的问题是:

    创建对象所付出的代价比较大

    没有必要创建多个问题

    提供一个全局访问点,就像C中的全局变量一样

3、常见的两种实现机制

3.1、常见实现一:只要加载Class文件,就创建对象

 1 package com.xinye.test.singleton;
 2 /**
 3  * 单例
 4  * @author xinye
 5  *
 6  */
 7 public class Singleton {
 8     
 9     private static final Singleton INSTANCE = new Singleton();
10     
11     private Singleton(){
12         
13     }
14     
15     public static Singleton getInstance(){
16         return INSTANCE;
17     }
18 }

3.2、常见的实现二:在第一次使用的时候创建对象,传说中的懒加载方式

  注意:

    这种情况下,如果使用在多线程环境中,需要使用同步机制

    对于一定会使用到这个单例的情况下,这种实现方式就比较扯淡了

          只有在创建这个对象代价特别大的情况下,懒加载的情况才有意义
    

 1 package com.xinye.test.singleton;
 2 /**
 3  * 
 4  * @author xinye
 5  *
 6  */
 7 public class SingletonLazy {
 8     
 9     private static SingletonLazy instance = null;
10     
11     private SingletonLazy(){
12         
13     }
14     public synchronized static SingletonLazy getInstance(){
15         if(instance == null){
16             instance = new SingletonLazy();
17         }
18         return instance;
19     } 
20 }

还有其他的实现单例模式的方法,比如静态私有内部类的方式,但造成代码可读性很垃圾,所以,永远不用那个!

3.3、使用示例:

 

 1 package com.xinye.test.singleton;
 2 /**
 3  * 
 4  * @author xinye
 5  *
 6  */
 7 public class TestSingleton {
 8 
 9     public static void main(String[] args) {
10         Singleton s1 = Singleton.getInstance();
11         Singleton s2 = Singleton.getInstance();
12         
13         System.out.println(s1);
14         System.out.println(s2);
15         
16         SingletonLazy sl1 = SingletonLazy.getInstance();
17         SingletonLazy sl2 = SingletonLazy.getInstance();
18         
19         System.out.println(sl1);
20         System.out.println(sl2);
21     }
22 
23 }

 

posted on 2014-08-12 15:10  wangwangheng  阅读(209)  评论(0编辑  收藏  举报