The Singleton of Design Pattern单态模式

本文详细介绍了单例模式的概念及其在应用程序中的重要性。通过具体的代码示例,展示了如何确保类的实例唯一,并提供了实例化的全局访问点。同时,通过一个简单的程序演示了单例模式的实际效果。

1 Singleton Definition 单态模式定义
       The main purpose is to gurantee that the instance of class has only one in the application.  some operations, such as connecting to database, are userful for only single instance.
        单态模式的主要作用是保证类的实例只有一个。在很多操作中,比如数据库连接等,这种单实例是很有用的。
 
2 singleton model单态模型


3 related singleton model codes:相关单态模式代码
namespace singleton
{
    public class singleton{
    private int _counter;
    private static singleton _instance;
    private static object _classLock=typeof(singleton);
    private singleton()
    {
        _counter = 0;
    }
    public static singleton CreateInstance()//global point to service
    {
        lock (_classLock)
        {
            if (_instance == null)
                instance = new singleton();
        }
            return _instance;
      }

    public void Counte()
    {
        lock (_classLock)//exclusive lock
            {
                _counter++;
            }
    }

     public int Counter
    {    
        get
            {
                return _counter;
            }
    }
  }

    class Program
    {
        static void Main(string[] args)
        {
            singleton hiron = singleton.CreateInstance();
            hiron.Counte();
            singleton hrg = singleton.CreateInstance();
            hrg.Counte();
            Console.WriteLine(hrg.Counter);
        }    
    }
}
excution result:
instance hiron and hrg will refer to the same instance actually, and the output is 2

转载于:https://www.cnblogs.com/Winston/archive/2008/05/05/1183077.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值