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


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

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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3