Top 15 Java Design Pattern Interview Questions and Answers

Design Patterns has been a hot topic when it comes to Java interviews. It is one of the most popular sections amongst the interviewers from which they test the interviewee’s awareness on how to solve a commonly occurring software problem. We are going to take a deep dive into the popular design pattern interview questions that one can come across in the Java interviews.

Read Also :  Singleton Design Pattern in Java

Q1 What are Java Design Patterns?

Java Design patterns are the best practices developed and evolved over a period of time by seasoned software developers to resolve any commonly encountered software development/design problem. They are not mandatory to implement but using them wisely can do wonders as far as software development is considered.

Q2 What are the different categories of Design Patterns?

Design patterns can be categorized into 3 types. These are given below:

1. Creational Patterns - These are concerned with the way an object is created or instantiation of a class. They give freedom to choose the right object creation strategy in a particular situation. They can be further classified into object creational and class creational patterns.

2. Structural Patterns - These design patterns are concerned with class and object composition in order to create larger structures. They work by identifying and simplifying the relationships between the entities.

3. Behavioral Patterns - These design patterns are more concerned with identifying the way in which objects communicate with each other.


Q3 What is Singleton Design Pattern?

Singleton design pattern is a sub type of creational pattern. It ensures that at any given instance, one and only one object of the class exists in JVM and provides a way to access to this object. These are widely implemented in applications while establishing database connection and configuring logging functionality.

Q4 How to implement a Singleton Java class?

Given below is the most common way to construct a Singleton class. It works well in single threaded environment but has some drawback in multithreaded environment which will be explained as part of next question.

public class Singleton {

     //reference variable
     private static Singleton instance;

     /* prevent instantiation from outside 
        of class by making constructor private.*/
     private Singleton(){}

     /* if object exists, return the existing 
        object. If not, create and return a
        new object.*/
     public static Singleton getInstance() { 
        if (instance == null) {
         instance = new Singleton(); 
        }
  
        return instance; 
     }

     public void displayMessage(){
        System.out.println("Java Hungry");
     }
}


Q5 What happens if the method returning instance of Singleton class is not synchronized in multi-threaded environment?

In case of multi-threaded environment, the non-synchronized accessor method of Singleton class may create more than one instance of the class. This can happen when two threads enter the condition to check if the instance already exists at the same time.
Since, both the threads will find that the instance does not exist, they will get a new object created and returned and thus, we will have more than one instance of the class available.

Q6 What are the different ways to create Singleton design pattern in Java?

Singleton pattern object can be created in following ways:

Eager Loading – In Eager loading, the object of singleton class gets created when the class is loaded into the memory. This method of implementation should be avoided as it creates the object even when it is not requested or used.

Lazy Loading – In Lazy loading, the object of singleton class is created when it is actually requested by the client. In this method, the object is created within the singleton instance accessor method. This is the desired way to create the singleton object as it will create the instance only when it is required by the client.

Q7 How can you create a thread safe Singleton class in Java?

Thread safe singleton class can be created in three ways. They are:

Double check locking method: Allows lazy initialization. Checks the existence of the instance before acquiring lock.


public class DoubleCheckSingleton {

     //reference variable

     private static DoubleCheckSingleton instance;

     /*prevent instantiation from outside of
       class by making constructor private*/

     private DoubleCheckSingleton(){}

     //instance accessor method

     public static DoubleCheckSingleton getInstance(){

            if(instance == null){

                synchronized (DoubleCheckSingleton.class) {

                      if(instance == null){

                            instance = new DoubleCheckSingleton();

                      }
                }
            }
            return instance;
     }

     //method with some logic

     public void displayMessage(){

          System.out.println("Java Hungry");

     }

}

Enum singleton implementation: Safest and shortest way to create singleton but has drawback of eager initialization.

public enum EnumSingleton {

      INSTANCE;

      //method with some logic

      public void displayMessage(){
           System.out.println("Java Hungry");
      }
}

Synchronized instance accessor method: Allow lazy initialization. Reduced performance as lock is acquired every time whenever the instance is required.

public class SynchronizedSingleton {

       //reference variable

       private static SynchronizedSingleton instance;

       /*prevent instantiation from outside of class
         by making constructor private */

       private SynchronizedSingleton(){}

       //synchronized instance accessor method

       public static synchronized SynchronizedSingleton getInstance(){


              if(instance == null){

                    if(instance == null){

                        instance = new SynchronizedSingleton();
                    }
              }
              return instance;
       }

       //method with some logic

       public void displayMessage(){

            System.out.println("Java Hungry");

       }

}

Q8 Is it possible to create a clone of a Singleton object?

Yes, it is possible to a create clone of singleton object if the class implements Cloneable interface.

Q9 How can the cloning of Single object be prevented?

It can be prevented by overriding clone() method and throwing an exception within it.

Q10 What is Factory Design Pattern?

It is a sub type of creational design pattern which provides a specification for instantiation of a class by using an interface or abstract class. The actual logic of instantiation is deferred to the subclasses based on the type of object needed. The client can get the desired object created without knowing the actual logic.

Q11 What is Abstract Factory Design Pattern?

It is also a sub type of creational design pattern and is used where we require one more layer of abstraction up and above a family of factory pattern objects. This is the reason that it is also referred as factory of factories. The abstract factory pattern creates factories which in turn create the objects by further deferring the object creation logic to their sub classes.

Q12 What is the difference between Factory and Abstract Factory Design Pattern?

The factory pattern uses inheritance whereas the abstract factory pattern uses composition as mechanism for object creation.

The factory pattern creates single object whereas abstract factory pattern creates a group of objects.

Q13 What is Builder Design Pattern?

It is a sub type of creation design pattern which is used to create complex object using simple objects. It is an alternative to Factory as well as Abstract Factory design pattern and is a better option to go with when lots of attributes are associated with the object.
It works by assembling the complex object step by step and providing a method to access the same.

Q14 Which design pattern is preferred for creating a complex object?

Builder design pattern is more suitable for creating complex object as it is an extension of Factory pattern and is created for solving the issues associated with Factory and Abstract Factory design patterns.

Q15 What is Prototype Design Pattern and when to use it?

It is a creational design pattern which is used in cases when a large number of instances of a class are required and these instances are almost identical but may have slightly different properties. This pattern is useful in cases wherever there is high time and cost overhead associated with the object creation. This pattern mainly works by creating clone of the existing object instead of creating a new instance every time so that performance is optimized.

That's all for the java design pattern interview questions. If you like this article then please share it with your friends.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry