单例模式

定义:确保一个类只有一个实例。并提供一个全局访问点。

经典代码:

public class Singleton {  

 private static Singleton singleton;  

 private   Singleton() {   

// TODO Auto-generated constructor stub  

}

   public static Singleton getInstance(){     

 if (singleton == null){

   singleton = new Singleton();

}      

      return singleton;

 }

}

但是经典代码有多线程的问题。

同步:

public class Singleton {  

 private static Singleton singleton;  

 private   Singleton() {   

// TODO Auto-generated constructor stub  

}

   public static synchronized Singleton getInstance(){     

 if (singleton == null){

   singleton = new Singleton();

}      

      return singleton;

 }

}

 

posted @ 2016-01-21 16:07  戎码一生  阅读(125)  评论(0编辑  收藏  举报