Computers

Design Patterns : Singleton

Motivation

It is important for some classes to have exactly one instance. As an example although there can be many printers in a system, there should be only one printer spooler. How do we ensure that a class has only one instance and that the instance is easily accessible within the network?

Intent

  • To ensure that a class has only one instance, and to provide a global point of access to it.
  • Regardless of the mechanics, the value of Singleton lies in centralizing authority in a single object.

Applicability

Use Singleton pattern when

  • 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.

Why is it a Responsibility Pattern?

Objects can usually act responsibly just by performing their own work. but some some objects take on further responsibilities such as;
  • Representing real-world entities
  • Coordinating work
  • Modeling the state of a system
When they have that extra responsibility to carry they become responsible for self and other clients too.

How to instantiate a single instance and global access?

The mechanics of Singleton are more memorable than its intent.It is easier to explain how to ensure that a class has only one instance than it is to say why you might want this restriction.You might categorize Singleton as a “creational” pattern.
One way create this instance as a static field in the class.
  • example: The Runtime class in java.lang includes the line:
–private static Runtime currentRuntime = new Runtime();

Lazy Initialization

The system might wait until the instance is first needed.
Example : A Factory class might make its single instance available with

public static Factory getFactory() {

if (factory == null) {

factory = new Factory();
// …

}

return factory;
}

Garbage Collection

Once you create a singleton instance it might get garbage-collected. If there is you might want to prevent this, specially if the objects has a significant startup cost or if it is gathering statistics.
Tip: This can be handled by having a reference to the object on the main process.

Share this post

Related Posts