Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How Singleton Java Object brings Varying Design Patterns

This article aims to bring in the concept of a singleton Java object that is regarded to bring in a lot of variety of design patterns or object designs.

Introduction

What is a design pattern? Let us look at the basic definition of the same. Well, it is nothing but a template for software development whose sole purpose is to define a specific process or technique that can be made use of as a building block for the software development. This is the most common issue that is actually faced by the developers these days. In this article, we will be looking at the concept of singleton that is regarded as an object which cannot be instantiated. Seems to be something wrong here? Well, you might be thinking we require an instance of an object before the same can be used.

We can create a singleton but developers won’t be able to instantiate it. This means that there will be a full control by the singleton on the way the same is being created.

Limitation of Singleton:

  • We can have just one singleton instance by JVM. Developers won’t be able to create another copy and this is done by preventing direct instantiation.

With such a limitation how it can be useful? We would like to see in majority of the design systems as to how the object is used and prevent others that include our copy as well so as to make copies of the same.

How to Prevent Direct Instantiation?

The new keyword is used so as to instantiate the object and this keyword also permit the users to come with an instance of object and also specifying the constructor of the class. The blank constructor also known by the name of default constructor gets invoked since the user cannot specify parameters.

We can have modifiers in the constructors- it could be public or private. This would allow controlling the list of classes that can have access to a constructor. Hence we need to come up with a private default constructor, marked as private in order to prevent direct instantiation.

Let us initiate with the definition of the SingletonObject class post which a default constructor will be provided, marked as private.

Listing1: Defining the SingletonObject class:

public class SingletonObject
{
	private SingletonObject()
	{
		// no code req'd
	}
}

How to obtain Singleton Instance?

There is a need of an acessor method so as to fetch the instance of the SingletonObject class. However the thing to note here is that it just allows the access of a single copy. The object can be mutually instantiated however there is a need to define a singleton reference. This is done so that subsequent calls to the accessor method have the ability to come up with the singleton. We will now define a getSingletonObject() and then store a copy of the singleton in a private member variable.

Listing2: Defining a getSingletonObject

public class SingletonObject
{
    private SingletonObject()
    {
        // no code req'd
    }

    public static SingletonObject getSingletonObject()
    {
      if (ref == null)
          // We can call this constructor
          ref = new SingletonObject();
      return ref;
    }

    private static SingletonObject ref;
}

We have getSingletonObject() method coming up with a singleton instance that needs to be assigned to a member variable that would return the singleton. The functionality of the singleton object can be extended by incorporating new methods. This is done to perform the tasks required by the singleton.

How thread issues can be avoided with Singleton

There should be any issues when threads call the getSingletonObject() method. Hence the ebst way to come out of this would be marking method as synchronized that prevents two threads from calling the getSingletonObject() method simultaneously. In case we have one thread entering the method just after the other, this can be done by calling the SingletonObject constructor twice and also by returning different values. One can make use of the keyword synchronised to the method declaration so as to modify the method.

Listing3: Addition of a synchronised keyword

public static synchronized
	 SingletonObject getSingletonObject()

Look at the below code that us used to clone a singleton object.

Listing4: Cloning a Singleton Object

public class Clone
{
	public static void main(String args[])
	  throws Exception
	{
	  // Get a singleton
	  SingletonObject obj = 
	  SingletonObject.getSingletonObject();

	  // Let's clone the object
	  SingletonObject clone = 
		(SingletonObject) obj.clone();
	}
}

If you would have noticed here, there is no clone () method defined in SingletonObject. However there is in the java.lang.Object class which it is inherited from and if we see the status of clone () method, it is marked as protected by default. It is quite probable that the design principles of the Singleton could easily get violate in case the SingletonObject extends another class that is not capable of supporting cloning. Hence the need is to incorporate a clone() method of our own and simultaneously throw a CloneNotSupportedExcception. This is just to make sure the existence of a singleton.

The below lists the source code for a SingletonObject: This can be used as a template for singletons.

Listing5: Illustrating the Source Code for a SingletonObject

public class SingletonObject
{
  private SingletonObject()
  {
    // no code req'd
  }

  public static SingletonObject getSingletonObject()
  {
    if (ref == null)
        // it's ok, we can call this constructor
        ref = new SingletonObject();		
    return ref;
  }

  public Object clone()
	throws CloneNotSupportedException
  {
    throw new CloneNotSupportedException(); 
    // that'll teach 'em
  }

  private static SingletonObject ref;
}

There would be no hassles in coming up with an implementation of the singleton pattern, you just need to block the constructor access, next would be the offering of a static method in order to obtain the singleton instance and then comes the prevention of cloning.

Conclusion

Let us conclude what we learnt today. We learn that a singleton is a class that cannot be instantiated more than once and is considered to be a useful in wide range of object designs.

I hope you liked the article, see you next time.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login