源码下载 | 网页特效 | 广告代码 | 站长必备 | 站长工具
会员投稿 投稿指南 RSS订阅
您当前的位置是:主页>网络编程>PHP教程>

PHP教程:典型的单例模式版本

www.jz123.cn  2009-03-20   来源:   中国建站    责任编辑(袁袁)    我要投递新闻

  有时,我们需要在应用程序中只允许存在一个类的实例。

  如windows的任务管理器,永远只可能出现一个,这就是典型的单例模式。

  单例模式提供一个全局的访问点,并且让外部无法对该类进行new()

  典型的单例模式版本

public sealed class Singleton  
{  
static Singleton instance=null;  
Singleton()  
{  
}  
public static Singleton Instance  
{  
get 
{  
if (instance==null)  
{  
instance = new Singleton();  
}  
return instance;  
}  
}  
}
public sealed class Singleton
{
static Singleton instance=null;
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}

  但这并不是一个好的代码,因为这样的代码不是安全的,很可能被其它线程修改。

  第二个版本:

public sealed class Singleton  
{  
static Singleton instance=null;  
static readonly object padlock = new object();  
Singleton()  
{  
}  
public static Singleton Instance  
{  
get 
{  
lock (padlock)  
{  
if (instance==null)  
{  
instance = new Singleton();  
}  
return instance;  
}  
}  
}  
}
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

  使用了lock关键字,确保只能有一个线程可以访问它。

上一篇:PHP中的单例只在整个页面周期内唯一 下一篇:PHP下载google相册到本地

评论总数:1 [ 查看全部 ] 网友评论


关于我们隐私版权广告服务友情链接联系我们网站地图