单例模式

http://baike.baidu.com/view/1859857.htm
单例模式一般有三种形式

//1.饿汉式

public class Singleton1 {

 

         private static Singleton1 instance = new Singleton1();

 

         private Singleton1() {

         }

 

         static Singleton1 getInstance() {

                   return instance;

         }

 

}


*************************************************************************************************************************************************************************

//2.懒汉式

public class Singleton2 {

 

         private static Singleton2 instance = null;

 

         private Singleton2() {

         }

 

         static Singleton2 getInstance() {

                   if (instance == null)

                            instance = new Singleton2();

                   return instance;

         }

}

*************************************************************************************************************************************************************************


//
双重锁的形式。

public class Singleton3 {

         private static Singleton3 instance = null;

         private Singleton3(){

                   //do something

         }

         public static Singleton3 getInstance(){

                   if(instance==null){

                            synchronized(Singleton3.class){

                                     if(null == instance){ 

                                               instance = new Singleton3();

                                     }

                            }

                   }

                   return instance;

         }

}

 

posted @ 2013-05-08 22:56  `仅此而已  阅读(147)  评论(0编辑  收藏  举报