单例的定义是:
确保一个类只有一个实例,并提供一个全局的访问此实例的入口。
其UML类图的示例如下:
在这个模式中,参与者包括:
- Singleton,定义一个实例化操作,让客户访问其唯一实例,实例化是一个类操作。另外还负责创建和维护其唯一实例。
class Singleton
{
private static Singleton _instance;
// Constructor is 'protected'
protected Singleton()
{
}
public static Singleton Instance()
{
// Uses lazy initialization.
// Note: this is not thread safe.
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
}
- 让类只有一个实例可以访问