Singleton

来源:互联网 发布:linux net ratelimit 编辑:程序博客网 时间:2024/05/01 06:05

Common uses

  • The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
  • Facade objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
  • Singletons are often preferred to global variables because:
    • They don't pollute the global namespace (or, in languages withnamespaces, their containing namespace) with unnecessary variables.
    • They permit lazy allocation and initialization, where global variables in many languages will always consume resources.

Class diagram


JAVA EXAMPLE:

public class Singleton {

   private static final Singleton INSTANCE = new Singleton();
 
   // Private constructor prevents instantiation from other classes
   private Singleton() {}
 
   public static Singleton getInstance() {
      return INSTANCE;
   }
 }
原创粉丝点击