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

Creating simple CSS spinner-loader

In today's article we will show you how to animate a basic loader that spins when some predefined action is defined, such as loading an image. That can be used…

Deepfakes Detection – An Emerging Technological Challenge

It is highly probable that while browsing the Internet, everyone of us has at some point stumbled upon a deepfake video. Deepfakes usually depict well-known people doing really improbable things…

7 Astonishing New Uses of Machine Learning

Recently a strange video published on YouTube caused a controversy – it was a funny take on Queen Elizabeth’s traditional Christmas message created by Channel 4, a British public-service television broadcaster. They…

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

Django vs. Laravel: Market Share Comparison

There are two leading frameworks in the web development segment: Django and Laravel. In this article, we prepared a Django and Laravel comparison focusing on their market share so that…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

A Java approach: While loop

Hello everyone and welcome back! After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called…

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…

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