C#面向对象设计模式纵横谈(2):Singleton 单件(创建型模式)
模式分类
|
| 目的 | |||
| 创建型 | 结构型 | 行为型 | ||
|
范
围 |
类 | 工厂方法(Factory Method) | 适配器(类,Adapter) | 解释器(Interpreter) 模板方法(Template Method) |
|
对
象 | 抽象工厂(Abstract Factory) 生成器(Builder) 原型(Prototype) 单件(Singleton) | 适配器(对象,Adapter) 桥接(Bridge) 组成(Composite) 装饰(Decorator) 外观(Facade) 享元(Flyweight) 代理(Proxy) | 职责链(Chain of Responsibility) 命 令(Command) 迭代器(Iterator) 中介者(Mediator) 备忘录(Memento) 观察者(Observer) 状 态(State) 策 略(Strategy) 访问者(Visitor) | |
动机(Motivation)
意图(Intent)
Singleton 模式实现
/**/
/// <summary>
/// 单线程 Singleton 模式实现
/// </summary>
public
class
Singleton
{
private static Singleton instance;

private Singleton()
{}//私有的构造器使得外部无法创建该类的实例
public static Singleton Instance
{
get
{
if ( instance == null )
{
instance = new Singletion();
}
return instance;
}
}
}

/**//// <summary>
/// 多线程 Singleton 模式实现
/// </summary>
public class Singleton

{
private static volatile Singleton instance = null;
private static object lockHelper = new Object();

private Singleton()
{} //私有的构造器使得外部无法创建该类的实例

public static Singleton Instance
{
get
{
if ( instance == null )
{
lock ( lockHelper )
{
if ( instance == null )
{
instance = new Singletion();
}
}
}
return instance;
}
}
}
/**/
/// <summary>
/// 多线程 Singleton 模式实现
/// </summary>
class
Singleton
{
public static readonly Singletion Instance = new Singleton();

private Singleton()
{}
}


/**/
//// 等同于:
/// <summary>
/// 多线程 Singleton 模式实现
/// </summary>
class
Singleton
{
public static readonly Singletion Instance;
static Singleton()
{
Instance = new Singleton();
}

private Singleton()
{ }
}
/**/
/// <summary>
/// 单线程 Singleton 模式实现
/// 支持参数化的构造器方式
/// </summary>
public
class
Singleton
{
public static readonly Singletion instance;
private Singleton(int x, int y)
{
this.x = x;
this.y = y;
}
public static Singleton GetInstance(int x, int y0
{
if ( instance == null )
{
instance = new Singleton(x, y);
}
else
{
instance.x = x;
instance.y = y;
}
return instance;
}
int x;
int y;
}

博客展示了多线程Singleton模式的实现代码。通过定义私有构造器防止外部创建实例,使用静态volatile变量和锁机制确保线程安全,实现单例模式。

206

被折叠的 条评论
为什么被折叠?



