单例,Singleton

来源:互联网 发布:战争雷霆pw42数据 编辑:程序博客网 时间:2024/06/16 04:09

单例的定义是:

确保一个类只有一个实例,并提供一个全局的访问此实例的入口。

其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;    }  }

使用场景:
  • 让类只有一个实例可以访问

0 0
原创粉丝点击