Pages

Friday, November 08, 2013

The Singleton Pattern

The Singleton Pattern got its name because it restricts instantiation of a class to a single object. This can be implemented by creating a method which creates an instance of the class if one doesn't exist, but returns the reference to the existing object, if already exists. Singletons are different from static classes as we can delay their initialization to a later point of time.

In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.

The applicability of the Singleton pattern is described as follows:
  • There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • When the sole instance should be extensible by sub-classing, and clients should be able to use an extended instance without modifying their code.
Singletons are useful but they shouldn't be overused. The Singleton pattern is useful when exactly one object is needed to coordinate others across a system.

They're often an indication that modules in a system are either tightly coupled or that logic is overly spread across multiple parts of a code base. Singletons can be more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating multiple instances, difficulty in stubbing dependencies and so on.

Read more about Singleton Patterns ...

No comments:

Post a Comment