Tuesday, October 10, 2017

Singleton Programming Design Pattern

What is the Singleton design pattern?

The concpet of restricting the instantiation of the a class to only and only to one object is called Singleton. As name suggests, it will restrict to create only one instance of a class. The calss will have a logic in place which will deny if the application will ask for more than one instance.

 

Code Lines

Let’s try to understand with an example:
We have an application which will bring the pay stub of an employee for current month. In a standarad system, there will be only one active salary account for the employee with the company. Because of this fact, we should only create one object of the employee’s salary account. In program, we are creating this object in a loop. So, what happens if we don’t have a design pattern which will restrict it to create more than one object. Application will create, rather overwrite an instance of the class.


Advantages


Accessibility


The most obvious advantage of the singleton pattern is accessibility. Consider the UIApplication class as an example. By importing the UIKit framework, the UIApplication singleton is accessible from anywhere in your project. Take a look at the following example of a UIViewController subclass.

Disadvantages


Global State


By creating a singleton, you're essentially creating global state. It's important that you're aware of this. A few years ago, Miško Hevery wrote a great article about the singleton pattern in which he explains why the pattern should be avoided. Miško emphasizes that global state is the main reason why singletons are harmful.

Dealing With Multithreading 

In the Android system, you can spin off multiple threads to perform different tasks. These threads can end up executing the same code block simultaneously. In the case of the Singleton class above, this could lead to the creation of multiple object instances, which violates the contract of a Singleton. So our Singleton code snippet method getInstance() is not thread safe. We'll now look at ways to make it thread safe.

Singleton is an elegant way of maintaining global state, but we should always question whether we need global state. Singleton pattern offers several advantages over global variables because it does the following:

1.    Enforces that only one instance of the class can be instantiated.

2.    Allows control over the allocation and destruction of the object.

3.    Provides thread-safe access to the object's global state.

4.    Prevents the global namespace from being polluting.


No comments: