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

PHP
php教程:mysql数据库操作的DB类
PHP教程:cookie和数组的结合实现购物车
php教程:mysql的常用语句
php教程:经典PHP代码
php编程中遇到的cookie的问题
php入门交流:鼓励学习PHP的新手
细数PHP程序的一些缺陷
说明PHP开发网站程序的优点
PHP+MYSQL网站开发中遇到的问题汇总
php教程:php设计模式介绍之工厂模式
ubuntu下apache2不能解释php程序故障
WIN2003+IIS6+PHP5根目录无法运行PHP程序
PHP+MYSQL网站开发中关于时间的问题
PHP正则表达式提取超链接及其标题
PHP中的Date()函数详细讲解
初学:apache与php基本配置
PHP串行化与JSON
php教程:php设计模式介绍之单条模式
PHP中不能使用exec(),system(),shell_system()等函数
PHP正则表达式从url中取得域名

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


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