单例(Singleton)模式
2004-11-28 22:58
627 查看
按照设计模式中的定义,Singleton模式的用途是"ensure a class has only one instance, and provide a global
point of access to it(确保每个类只有一个实例,并提供它的全局访问点)";
using System;
namespace DesignPatters.Singleton
{
public class Singleton
{
public static Singleton Instance()
{
if (_instance == null)
{
lock (typeof(Singleton))
{
if (_instance == null)
{
_instance = new Singleton();
}
}
}
return _instance;
}
public int NextValue()
{
return ++count;
}
protected Singleton(){}
private static volatile Singleton _instance = null;
private int count = 0;
}
public class MainClient
{
[STAThread]
static void Main()
{
Singleton sg1 = Singleton.Instance();
for (int i = 0; i < 20; i++)
Console.WriteLine("Next Value: {0}",
sg1.NextValue() + " - sg1");
Singleton sg2 = Singleton.Instance();
Console.WriteLine("Next Value: {0}",
sg2.NextValue() + " - sg2");
}
}
}
相关文章推荐
- 千年零一虫
- ATL实现Connection Point的一种简单的方法
- 哪位仁兄帮一下编个小程序
- PHP 的 MySQL 操作类,跟手册上的函数一样用,但是更方便了。多说无益,看了就知道了。
- 在线等,一个十万火急的问题
- duwamish7的感悟!
- oracle中的分页
- SELECT TOP N 问题
- 英雄无敌程序员版
- DirectX.Capture
- 力争最简单把*、&说清楚
- 一个画图类,类似ms_chart的线图,适用于科学仿真数据分析(一)
- 学ASP.NET学什么?
- 怎样为任何控件和区域添加提示信息:用自己封装的CTip类
- 从注册表中还原MSNMessenger口令
- 使用C#开发COM+组件
- 2004/09/17又重装系统了——知道vsconfig.xml是谁生成的吗?
- 纯编码实现数据库的建立或压缩
- PowerShell 修复 Robocopy的权限问题