Monday, 1 April 2013

Singleton Design Pattern

Intro

  • The singleton design pattern restricts the instantiation of class to one object.
  • This is useful when one object is needed across system.
  • System that operates efficient when only one object exists.
  • System restricts the instantiation to certain number of objects.
  • The singleton object is available in global state, even if the object/class is not used. Using static method it can be avoid.

Implementation 

  • Implementation of singleton must statisfy single instance and global access principles.
  • It requires a mechanism accessing singleton class without re-creating a class object .
  • And mechanism to persist values of class members among class objects.
  • The singleton pattern is implemented by creating a class with method that creates new instance if one does not exist. If an instance already exist, it returns a reference to that object.
  • Singleton class construct should be private, so that object cannot be instantiate in other ways.
  • Singleton must be carefully implemented in multi-thread programming, 'cause if two threads are execute the creation method at same time when singleton doesn't exist, they both must check the availability of instance and only one should create new.
  • Singleton can be implemented as a static instance.
  • Singleton can be lazily constructed.
  • Requiring no memory or resource until needed.

Eager Initialization

  • If the program always need an instance or if the cost of creating instance is not too large in terms of time/resources.
  • The instance is not constructed/create until the class is used.
  • There is no need to synchronize the method, meaning that all thread will see the same instance and no locking required.
  • The final keyword means that the instance cannot be redefined ensuring only one instance is exists. 

No comments:

Post a Comment