码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-01-21 19:04:28      阅读:123      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!