当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP教程:典型的单例模式版本

PHP
PHP中for循环语句的几种“变态”用法
用PHP与XML联手进行网站开发
PHP程序漏洞产生的原因和防范方法
利用PHP编程防范XSS跨站脚本攻击
使用PHP往Windows系统中添加用户
PHP Shell的编写(改进版)
PHP开发中接收复选框信息的方法
PHP程序加速探索之服务器负载测试
PHP实现首页自动选择语言转跳
十天学会php之第一天
十天学会php之第二天
十天学会php之第三天
十天学会php之第四天
十天学会php之第五天
十天学会php之第六天
十天学会php之第七天
十天学会php之第八天
十天学会php之第九天
十天学会php之第十天
Web开发源代码:PHP生成静态页面的类

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 32 ::
收藏到网摘: n/a

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

如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关键字,确保只能有一个线程可以访问它。