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

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

GAN Generated Images

Let’s play a game - can you guess what these portraits have in common?  They all depict non-existent people. All these images were created by artificial intelligence. We could say, that…

A Java approach: condtional structures

Hello everyone and welcome back! The previous times we have introduced the concept of variable, trying to define some basic concepts about it.  However, some situations suggest that the concept of…

3 awesome ways technology is helping us combat the COVID pandemic

Times are hard now, that humanity once more stumbled into a terrible pandemic. But in comparison to the poor folks back in 1918 when the Spanish flu was on wreaking havoc,…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

Data structures in Java - Linked Lists

With 2020 we are going to look at a new aspect of programming: data structures. It is often the case that everyone uses structures provided by the various programming languages.…

A Java approach: variables - use case

Hello all friends and welcome back! After the introduction made on the variables, we try to analyse some critical issues that may arise in quite common situations. Let's start by analysing…

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