首页 > 其他 > 详细

单例模式

时间:2016-01-21 19:01:42      阅读:279      评论:0      收藏:0      [点我收藏+]

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

技术分享

经典代码:

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;

 }

}

 

单例模式

原文:http://www.cnblogs.com/skys-li/p/5148617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!