`

one note of Head first design patterns(singleton pattern)

阅读更多

I read the singleto pattern with the  head first  design pattern yestarday evening.i will review it .

      First of all ,we should konw about the offical definition of the pattern,here is it .the singleto

ensures that a class has only one instance, and provide a global point of access to it .it  is used

to treat with the following  situation.when we just need one instance of a class,what's more.the

object needs to be accessed at a global level.there are two forms about this pattern as follows:

java 代码
  1. public class Singleto {      
  2.      
  3.      private static Singleto instance  ;      
  4.      
  5.      private Singleto(){ }      
  6.            
  7.      public static synchronized Singleto getInstance(){      
  8.             
  9.            if(instance==null){      
  10.                      
  11.                 instance = new Singleto();      
  12.            }else       
  13.                 return instance ;      
  14.      }      
  15.      
  16.      
  17. }   
  18. //the synchroinzed key ensure the only one instance at the mutilthread access.

 

java 代码
  1. public class Singleto {      
  2.      
  3.      private static Singleto instance = new Singleto() ;      
  4.      
  5.      private Singleto(){ }      
  6.            
  7.      public static Singleto getInstance(){      
  8.             
  9.               return instance ;      
  10.      }      
  11.      
  12.      
  13. }    
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics