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

 
 
 
 
 

Related Posts