Java: introduction to Design Patterns and Singleton Pattern



Anyone with even a minimum experience of programming, should have realized that the majority of the problems have common elements. In fact we often find problems with the same pattern but in different contexts. 
For example, a management software for s supermarket and the one for a great industry will operate on different data but the functions implemented could be similar. By extending this type of concept to all programming, it can be said that the problems encountered in developing large software projects are often recurrent and predictable.
This type of reasoning gives rise to patterns, better known as design patterns.

What does it mean to use design patterns

Using design patterns means not to invent from the beginning new solutions but using working and consolidated solutions developed over the years. The idea is of providing a common "dictionary" to the majority of the developers.

Trying to give a theorical definition, a pattern is a collection of classes and objects that communicate with each other adaptable to solve a recurrent problem in a specific context.

The important thing is that they were designed as non-domain-specific, so they are not intended for specific applications, but are reusable in parts of different applications.

This type of design is commonly used also in java classes like Iterator.

Nowadays, patterns can be sorted as shown below:

  • creational patterns: they deal with the objects creation process;
  • structural patterns: they deal with the classes and objects' composition;
  • behavioral patterns: they deal with the interaction and the responsibility distribution among classes;

A very simple example: Singleton

The need of this kind of design pattern is originated from the fact that we could need a class with one and only one instance.

The implementation, possibly, has to be thread-safe. Let's look at an example:

Classical implementation

Here is the UML diagram:

Singleton

public class Singleton{
/*
This will be the only instance of the class
Every access will be through this instance
and no instance will be created anymore
*/
private static Singleton instance = null; 
/*
private constructor to avoid other instances to be created
*/
private Singleton(){
}
/*
Unique access point 
*/
public static Singleton factory(){
//create the object if it doesn't exist
if(instance==null)
instance = new Singleton();
return instance;
}
//other methods
}

This kind of implementation is not suitable for a multi-threading context. A possible modification could be:

public class Singleton{
/*
This will be the only instance of the class 
Every access will be through this instance 
and no instance will be created anymore
*/
private static Singleton instance = null; 
/*
private constructor to avoid other instances to be created
*/
private Singleton(){
}
private synchronized static Singleton createInstance(){
if(instance==null)
instance=new Singleton();
return instance;
}
public static Singleton factory(){
if(instance==null)
//invoke the synchronized method only if
//the instance doesn't exist
createInstance();
return instance;
}
//other methods.
}

Understanding the code

The two examples carry out similar functions even in in slightly different ways.

The first example has a static attribute that represents the only accessible instance of the class. The constructor has been made private in order to avoid the creation of other instances of the class.

The access to the class can happen only through the method factory that checks the static attribute state. If it doesn't exist, it is instantiated. The method ends returning to the caller the attribute.

There will be two possible cases:

  • instance == null: the method will instantiate "instance" and return it to the caller;
  • instance != null: the method return to the caller the pointer to instance;

At first sight, the implementation is relatively easy for anyone who has a little bit of programming experience. In a multithread situation some synchronization problems may occurr, so a thread-safe version has been realized.

The logic of the second version is exactly the same as the first, like the final result, but with a slightly different application logic.

The first thing that we can notice is that in the thread-safe version there are two methods despite of the first where there were only one. The first method is necessarily synchronized in order to guarantee a correct synchronization amont the threads.

Remeber that a synchronized method is a method such that when a thread call the synchronized method on an object, every other thread that call that method later suspend its execution until the execution of the method that has been called first, ends.

The method createInstance() is responsible for checking the attribute status and based on its value, instantiate it or not.

Factory is a wrapper for the createInstance() methdo, checking also the instance attribute state.

This double check, that could seem to be without any sense, is useful in order to decrease the overhead. Strategies like this are called double-checked locking.

There are other strategies to implement a singleton that are more complex that decrease the overhead too.

A possible alternative could be:

public class Singleton{
	private static Singleton instance = null; 
	private Singleton(){
	}
	public static Singleton getIstance() {
        if(istance==null)
                synchronized(Singleton.class) {
                        if( instance == null )
                                istance = new Singleton();
                        }
        return istance;
}
	//eventuali altri metodi
}
 

Must be said that nowadays several criticisms are made towards this model, because the Singleton Pattern problem is misunderstood and often used to introduce the concept of global variables in its own system by introducing the application in the global state in the application domain. This is bad, because global variables are notoriously not concerned with the structure of the program.

Another strong criticism that is made concern with the fact that the majority of the Singleton classes don't respect the general principles of the software engineering, working as an aggregator for different functions without any relation between each other, introducing the dependence concept, violating the concept of single responsibility.

In fact, standing to the software engineering principles, every element of the software must have only one responsibility that must be encapsulated by the element itself.

The Singleton allows the access by a static method and this charateristic makes it possible to use the instance within other methods without going through the parameters. Despite it could seem convenient, it means that the methods' signature don't show the dependencies anymore. This means that the programmer has to know the internal logic of the code. In this way, the code is more difficult to test and debug.

A third defect is the violation of the Liskov's Substitution Principle. In fact, since it does not present inheritance relationships, it is impossible to replace the objects linked by a family relationship.

Despite of all the criticisms, if not abused, the Singleton can represent a resource, although we will see more strategies to solve similar problems later.wink

 
 
Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.

 
 
 

Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration