Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Singleton Pattern

Avatar for Jerry Bian Jerry Bian
February 02, 2013

Singleton Pattern

a slide of Singleton Pattern when I was a trainee in M&M

Avatar for Jerry Bian

Jerry Bian

February 02, 2013

Other Decks in Programming

Transcript

  1. When to Use it? 3 SQL Connection Pooling in .NET

    Singleton keeps track of all the available connections and hands them out as they are available. (Here) Applicability o 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时 o 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改 代码就能使用一个扩展的实例时
  2. Implementation of C# 4 //client code Manager Test= Manager.GetInstance(); //another

    client code Manager Test1= Manager.GetInstance(); ONLY ONE INSTANCE!!!
  3. Lazy initialization 7  Lazy initialization  延迟初始化 (懒汉模式) 

    这个单例类的唯一实例是在第一次使用GetInstance()时初始化的  Lazy<T> in .NET 4.0/4.5 (msdn)
  4. Eager initialization 8  Eager initialization  热初始化 (饿汉模式) 

    程序经常需要用到这个单例,或者创建这个单例在性能方面消耗很小 | 主动创建  C#使用静态初始化来完成eager initialization | CLR会自动解决多线程同步问题
  5. Advantage 9 » 对唯一实例的受控访问  因为Manager类封装它的唯一实例,所以它可以严格的控制客户怎样以及何时访问它 » 缩小命名空间  是对全局变量的一种改进。避免了那些存储唯一实例的全局变量污染命名空间

    » 允许对操作和表示的精化  Manager类可以有子类,而且用这个扩展类的实例来配置应用是很容易的 » 允许可变数目的实例  由于对唯一实例的控制,可以有很大的便利和权限来控制应用所使用的实例数目
  6. Drawback 10  In theory: when you need to restrict

    the instantiation of an object to one instance. In practice: never. Ref: http://stackoverflow.com/questions/3319434/singleton-pattern 1.违反了单一职责原则。 2.耦合度过大。 3.单元测试基本无法进行,因为单元测试中各个测试用例是彼此独立的, 而单例模式下这是违反的。 4.开发混淆,造成困惑。 There‘s at most a can use but there no need.