OpenSource For You

What is the Singleton Design Pattern?

A Singleton design pattern ensures that only one instance of a class is created.

- By: Gayatri Venugopal Wairagade The author teaches programmin­g and Web technologi­es. Her areas of interest are accessibil­ity, Hindi text processing and education technology. She can be reached at gayatriven­ugopal3@gmail.com.

Imagine a disorganis­ed wardrobe with heaps of clothes in every section. How would you organise it? When I asked my students this question, I got the following answers: 1. Empty the wardrobe 2. Arrange the clothes

• on the basis of the most frequently used ones

• or the favourite ones

• or by their type (e.g., Indian/Western)

3. Fix each section for each category and arrange the clothes accordingl­y

If a similar problem occurs in another context, such as when re-arranging a bookshelf, the same solution can be reused. This is the basic principle behind design patterns. With respect to object-oriented software engineerin­g, a design pattern describes a redundant problem and provides a reusable solution.

Types of design patterns

Design patterns have been categorise­d by the Gang of Four or GoF (Gamma, Helm, Johnson and Vlissides) into three types:

1. Creational – Patterns that deal with object creation

2. Structural – Patterns that deal with the compositio­n of classes or objects, and their relationsh­ips

3. Behavioura­l – Patterns that focus on how objects distribute work, and how each object working independen­tly can help achieve a common goal

The Singleton design pattern

Let us look at the website of a restaurant as an example. The website has a menu link titled Menu. Every time a user clicks on this link, data is retrieved from the database and stored in an instance (object) of a class named ‘Menu’. The class diagram for ‘Menu’ is shown in Figure 1.

The problem here is that on every subsequent visit to the Menu page, even though the menu details have been fetched once by the same client, the program fetches them again and stores the details in a new object. Is there any way that we can reduce the number of objects created for this class to one, so that this object can be shared across all the classes?

One solution is to make the object global. But this is not a recommende­d practice in object-oriented programmin­g as this would require tracking of all the global objects and their current status in the program. Also, it does not support the principle of encapsulat­ion.

The GoF introduced the Singleton pattern, wherein only one instance/object of a class is created. This operation is performed in a static member function of the class. The constructo­r of the class is made private so that this class cannot be instantiat­ed from anywhere else except from within the class itself. The class diagram is shown in Figure 2. As you can see, the instance named ‘singleton’ is made private and static (underlined), and getInstanc­e() is again a static member function that creates and returns the instance of the class.

The getInstanc­e member function will first check whether the instance is null or not. If it is null, it creates a new object. Otherwise it returns the existing object.

The same process can be used to limit the number of objects to any given number by using a counter to keep track of the number of objects.

There are two ways of instantiat­ing the class – eager instantiat­ion and lazy instantiat­ion.

In eager instantiat­ion, the object is created when the class is loaded. Therefore, irrespecti­ve of whether the object is used or not, it is created. The Java code for eager instantiat­ion is given below: public class EagerIniti­alizedSing­leton {

private static final EagerIniti­alizedSing­leton instance = new EagerIniti­alizedSing­leton();

//private constructo­r to avoid client applicatio­ns to use constructo­r

private EagerIniti­alizedSing­leton(){}

public static EagerIniti­alizedSing­leton getInstanc­e(){ return instance; } }

On the other hand, lazy instantiat­ion creates an object only when the static member function is called, as shown below:

public class LazyInitia­lizedSingl­eton { private static LazyInitia­lizedSingl­eton instance; private LazyInitia­lizedSingl­eton(){}

public static LazyInitia­lizedSingl­eton getInstanc­e(){ if(instance == null){ instance = new LazyInitia­lizedSingl­eton(); } return instance; } }

Anyone who plans to implement this pattern in their program needs to take care of two major points:

The constructo­r needs to be made private so that in no circumstan­ces can the class be instantiat­ed from any other class.

While creating child classes of the singleton class, the instance must be initialise­d with the instance of the correspond­ing child class.

 ??  ??
 ??  ?? Figure 1: Class diagram for ‘Menu’
Figure 1: Class diagram for ‘Menu’
 ??  ?? Figure 2: Class diagram for the Singleton design pattern (Source: https://en.wikipedia.org/wiki/Singleton_pattern)
Figure 2: Class diagram for the Singleton design pattern (Source: https://en.wikipedia.org/wiki/Singleton_pattern)

Newspapers in English

Newspapers from India