Prepare Interview

Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Java Design Patterns Interview Questions and Answers

Freshers / Beginner level questions & answers

Ques 1. What is design patterns?

Design patterns are tried and tested way to solve particular design issues by various programmers in the world. Design patterns are extension of code reuse.

Is it helpful? Add Comment View Comments
 

Ques 2. Can you name few design patterns used in standard JDK library?

Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and various other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and Observer pattern which is used in Swing and many event listener frameworks.

Is it helpful? Add Comment View Comments
 

Ques 3. What is Singleton design pattern in Java ? write code for thread-safe singleton in Java.

Singleton pattern focus on sharing of expensive object in whole system. Only one instance of a particular class is maintained in whole application which is shared by all modules. Java.lang.Runtime is a classical example of Singleton design pattern. From Java 5 onwards you can use enum to thread-safe singleton.

Is it helpful? Add Comment View Comments
 

Ques 4. What is main benefit of using factory pattern? Where do you use it?

Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you can later replace original implementation of Products or classes with more advanced and high performance implementation without any change on client layer.

Is it helpful? Add Comment View Comments
 

Ques 5. What is observer design pattern in Java?

Observer design pattern is based on communicating changes in state of object to observers so that they can take there action. Simple example is a weather system where change in weather must be reflected in Views to show to public. Here weather object is Subject while different views are Observers.

Is it helpful? Add Comment View Comments
 

Ques 6. Give example of decorator design pattern in Java ? Does it operate on object level or class level?

Decorator pattern enhances capability of individual object. Java IO uses decorator pattern extensively and classical example is Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading and writing for improved performance.

Is it helpful? Add Comment View Comments
 

Ques 7. What is decorator design pattern in Java?

  • Decorator design pattern is used to enhance the functionality of a particular object at run-time or dynamically.
  • At the same time other instance of same class will not be affected by this so individual object gets the new behavior.
  • Basically we wrap the original object through decorator object.
  • Decorator design pattern is based on abstract classes and we derive concrete implementation from that classes,
  • It’s a structural design pattern and most widely used.

Is it helpful? Add Comment View Comments
 

Ques 8. What is Factory Design Pattern with example?

Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

We're going to create a Mobile interface and concrete classes implementing the Mobile interface. A factory class MobileFactory is defined as a next step.

FactoryPatternDemo, our demo class will use MobileFactory to get a Mobile object. It will pass information (SAMSUNG / SONY / BLACKBERRY) to MobileFactory to get the type of object it needs.

Step 1: Create an interface.

Mobile.java

public interface Mobile {

   void draw();

}


Step 2

Create concrete classes implementing the same interface.

Sony.java

public class Sony implements Mobile {

   @Override

   public void draw() {

      System.out.println("Inside Sony::draw() method.");

   }

}


Blackberry.java

public class Blackberry implements Mobile {

   @Override

   public void draw() {

      System.out.println("Inside Blackberry::draw() method.");

   }

}


Samsung.java

public class Samsung implements Mobile {

   @Override

   public void draw() {

      System.out.println("Inside Samsung::draw() method.");

   }

}


Step 3

Create a Factory to generate object of concrete class based on given information.

MobileFactory.java

public class MobileFactory {

   //use getMobile method to get object of type Mobile 

   public Mobile getMobile(String MobileType){

      if(MobileType == null){

         return null;

      }

      if(MobileType.equalsIgnoreCase("SAMSUNG")){

         return new Samsung();

      } else if(MobileType.equalsIgnoreCase("SONY")){

         return new Sony();

      } else if(MobileType.equalsIgnoreCase("BLACKBERRY")){

         return new Blackberry();

      }

      return null;

   }

}


Step 4

Use the Factory to get object of concrete class by passing an information such as type.

FactoryPatternDemo.java

public class FactoryPatternDemo {

   public static void main(String[] args) {

      MobileFactory MobileFactory = new MobileFactory();

      //get an object of Samsung and call its draw method.

      Mobile Mobile1 = MobileFactory.getMobile("SAMSUNG");


      //call draw method of Samsung

      Mobile1.draw();


      //get an object of Sony and call its draw method.

      Mobile Mobile2 = MobileFactory.getMobile("SONY");


      //call draw method of Sony

      Mobile2.draw();


      //get an object of Blackberry and call its draw method.

      Mobile Mobile3 = MobileFactory.getMobile("BLACKBERRY");


      //call draw method of Blackberry

      Mobile3.draw();

   }

}


Step 5

Verify the output.

Inside Samsung::draw() method.

Inside Sony::draw() method.

Inside Blackberry::draw() method.

Is it helpful? Add Comment View Comments
 

Ques 9. What is Abstract Factory Design Patter in Java with example?

Abstract Factory patterns works around a super-factory which creates other factories. This factory is also called as Factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects, without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

We're going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We create an abstract factory class AbstractFactory as next step. Factory classes MobileFactory and ColorFactory are defined where each factory extends AbstractFactory. A factory creator/generator class FactoryProducer is created.

AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (SAMSUNG / SONY / BLACKBERRY for Mobile) to AbstractFactory to get the type of object it needs. It also passes information (RED / GREEN / BLUE for Color) to AbstractFactory to get the type of object it needs.

Step 1
Create an interface for Mobiles.
Mobile.java
public interface Mobile {
   void make();
}

Step 2
Create concrete classes implementing the same interface.
Sony.java
public class Sony implements Mobile {
   @Override
   public void make() {
      System.out.println("Inside Sony::make() method.");
   }
}

Blackberry.java
public class Blackberry implements Mobile {
   @Override
   public void make() {
      System.out.println("Inside Blackberry::make() method.");
   }
}

Samsung.java
public class Samsung implements Mobile {
   @Override
   public void make() {
      System.out.println("Inside Samsung::make() method.");
   }
}

Step 3
Create an interface for Colors.
Color.java
public interface Color {
   void fill();
}

Step4
Create concrete classes implementing the same interface.
Red.java
public class Red implements Color {
   @Override
   public void fill() {
      System.out.println("Inside Red::fill() method.");
   }
}

Green.java
public class Green implements Color {
   @Override
   public void fill() {
      System.out.println("Inside Green::fill() method.");
   }
}

Blue.java
public class Blue implements Color {
   @Override
   public void fill() {
      System.out.println("Inside Blue::fill() method.");
   }
}

Step 5
Create an Abstract class to get factories for Color and Mobile Objects.
AbstractFactory.java
public abstract class AbstractFactory {
   abstract Color getColor(String color);
   abstract Mobile getMobile(String shape) ;
}

Step 6
Create Factory classes extending AbstractFactory to generate object of concrete class based on given information.
MobileFactory.java
public class MobileFactory extends AbstractFactory {
   @Override
   public Mobile getMobile(String shapeType){
      if(shapeType == null){
         return null;
      }
      if(shapeType.equalsIgnoreCase("SAMSUNG")){
         return new Samsung();
      } else if(shapeType.equalsIgnoreCase("SONY")){
         return new Sony();
      } else if(shapeType.equalsIgnoreCase("BLACKBERRY")){
         return new Blackberry();
      }
      return null;
   }
   
   @Override
   Color getColor(String color) {
      return null;
   }
}

ColorFactory.java
public class ColorFactory extends AbstractFactory {
   @Override
   public Mobile getMobile(String shapeType){
      return null;
   }
   
   @Override
   Color getColor(String color) {
      if(color == null){
         return null;
      }
      if(color.equalsIgnoreCase("RED")){
         return new Red();
      } else if(color.equalsIgnoreCase("GREEN")){
         return new Green();
      } else if(color.equalsIgnoreCase("BLUE")){
         return new Blue();
      }
      return null;
   }
}

Step 7
Create a Factory generator/producer class to get factories by passing an information such as Mobile or Color
FactoryProducer.java
public class FactoryProducer {
   public static AbstractFactory getFactory(String choice){
      if(choice.equalsIgnoreCase("SHAPE")){
         return new MobileFactory();
      } else if(choice.equalsIgnoreCase("COLOR")){
         return new ColorFactory();
      }
      return null;
   }
}

Step 8
Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type.
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
   public static void main(String[] args) {

      //get shape factory
      AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");

      //get an object of Mobile Samsung
      Mobile shape1 = shapeFactory.getMobile("SAMSUNG");

      //call make method of Mobile Samsung
      shape1.make();

      //get an object of Mobile Sony
      Mobile shape2 = shapeFactory.getMobile("SONY");

      //call make method of Mobile Sony
      shape2.make();
      
      //get an object of Mobile Blackberry 
      Mobile shape3 = shapeFactory.getMobile("BLACKBERRY");

      //call make method of Mobile Blackberry
      shape3.make();

      //get color factory
      AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");

      //get an object of Color Red
      Color color1 = colorFactory.getColor("RED");

      //call fill method of Red
      color1.fill();

      //get an object of Color Green
      Color color2 = colorFactory.getColor("Green");

      //call fill method of Green
      color2.fill();

      //get an object of Color Blue
      Color color3 = colorFactory.getColor("BLUE");

      //call fill method of Color Blue
      color3.fill();
   }
}

Step 9
Verify the output:
Inside Samsung::make() method.
Inside Sony::make() method.
Inside Blackberry::make() method.
Inside Red::fill() method.
Inside Green::fill() method.
Inside Blue::fill() method.

Is it helpful? Add Comment View Comments
 

Ques 10. What is Singleton Design Pattern with example in java design patterns?

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object.

This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.

SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object.

Step 1
Create a Singleton Class.
SingleObject.java
public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java
public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}

Step 3
Verify the output:
Hello World!

Is it helpful? Add Comment View Comments
 

Ques 11. What is MVC design pattern in java design patterns?

MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
View - View represents the visualization of the data that model contains.
Controller - Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps View and Model separate.

We're going to create a Employee object acting as a model.EmployeeView will be a view class which can print employee details on console and EmployeeController is the controller class responsible to store data in Employee object and update view EmployeeView accordingly.
MVCPatternDemo, our demo class will use EmployeeController to demonstrate use of MVC pattern.

Step 1
Create Model.
Employee.java
public class Employee {
   private String salary;
   private String name;
   public String getSalary() {
      return salary;
   }
   public void setSalary(String salary) {
      this.salary = salary;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Step 2
Create View.
EmployeeView.java
public class EmployeeView {
   public void printEmployeeDetails(String employeeName, String employeeSalary){
      System.out.println("Employee: ");
      System.out.println("Name: " + employeeName);
      System.out.println("Salary: " + employeeSalary);
   }
}

Step 3
Create Controller.
EmployeeController.java
public class EmployeeController {
   private Employee model;
   private EmployeeView view;

   public EmployeeController(Employee model, EmployeeView view){
      this.model = model;
      this.view = view;
   }

   public void setEmployeeName(String name){
      model.setName(name);
   }

   public String getEmployeeName(){
      return model.getName();
   }

   public void setEmployeeSalary(String salary){
      model.setSalary(salary);
   }

   public String getEmployeeSalary(){
      return model.getSalary();
   }

   public void updateView(){
      view.printEmployeeDetails(model.getName(), model.getSalary());
   }
}

Step 4
Use the EmployeeController methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
public class MVCPatternDemo {
   public static void main(String[] args) {

      //fetch employee record based on his roll no from the database
      Employee model  = retriveEmployeeFromDatabase();

      //Create a view : to write employee details on console
      EmployeeView view = new EmployeeView();

      EmployeeController controller = new EmployeeController(model, view);

      controller.updateView();

      //update model data
      controller.setEmployeeName("Craig");

      controller.updateView();
   }

   private static Employee retriveEmployeeFromDatabase(){
      Employee employee = new Employee();
      employee.setName("Maxwell");
      employee.setSalary("30000");
      return employee;
   }
}

Step 5
Verify the output:
Employee: 
Name: Maxwell
Salary: 30000
Employee: 
Name: Kate
Salary: 30000

Is it helpful? Add Comment View Comments
 

Most helpful rated by users:

Related interview subjects

Core Java interview questions and answers - Total 306 questions
Tomcat interview questions and answers - Total 16 questions
Apache Wicket interview questions and answers - Total 26 questions
Java Applet interview questions and answers - Total 29 questions
JAXB interview questions and answers - Total 18 questions
JMS interview questions and answers - Total 64 questions
Log4j interview questions and answers - Total 35 questions
Struts interview questions and answers - Total 84 questions
RMI interview questions and answers - Total 31 questions
Apache Camel interview questions and answers - Total 20 questions
JDBC interview questions and answers - Total 27 questions
Java 11 interview questions and answers - Total 24 questions
JPA interview questions and answers - Total 41 questions
EJB interview questions and answers - Total 80 questions
GWT interview questions and answers - Total 27 questions
Kotlin interview questions and answers - Total 30 questions
Glassfish interview questions and answers - Total 8 questions
Google Gson interview questions and answers - Total 8 questions
JSP interview questions and answers - Total 49 questions
J2EE interview questions and answers - Total 25 questions
Apache Tapestry interview questions and answers - Total 9 questions
Java Swing interview questions and answers - Total 27 questions
Java Mail interview questions and answers - Total 27 questions
Hibernate interview questions and answers - Total 52 questions
JSF interview questions and answers - Total 24 questions
Java 8 interview questions and answers - Total 30 questions
Java 15 interview questions and answers - Total 16 questions
JBoss interview questions and answers - Total 14 questions
Web Services interview questions and answers - Total 10 questions
RichFaces interview questions and answers - Total 26 questions
Servlets interview questions and answers - Total 34 questions
Java Beans interview questions and answers - Total 57 questions
Spring Boot interview questions and answers - Total 50 questions
JUnit interview questions and answers - Total 24 questions
Spring Framework interview questions and answers - Total 53 questions
Java Design Patterns interview questions and answers - Total 15 questions
©2023 WithoutBook