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

PHP
AJAX在PHP中的简单使用
vim下高亮显示php代码
用 PHP 使 Web 数据分析进入更高境界
用Apache与MySQL整合实现基本身份认证
通用PHP动态生成静态HTML网页的代码
自己轻松修复Discuz!数据库技巧
PHP在Web开发领域的优势在哪?
php4和php5单态模式(Singleton Pattern)写法
使用Xdebug优化你的php程序
PHP学习入门的一些基础知识
关于正则表达式学习
浅谈PHP开发团队的管理之道
传奇的诞生,PHP三位创始人简介
利用PHP制作简单的内容采集器
PHP精确到每一秒钟的在线人数显示代码
一些PHP学习过程中的心得和经验
WINDOWS服务器安装多套PHP的另类解决方案
让你的PHP引擎全速运转的三个简单绝招
大型系统上PHP令人不爽的九大原因
php的计数器程序

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 39 ::
收藏到网摘: 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关键字,确保只能有一个线程可以访问它。