Prepare Interview

Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Java Design Patterns Interview Questions and Answers

Experienced / Expert level questions & answers

Ques 1. What is Observer Design Pattern in java design patterns?

Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.

Observer pattern uses three actor classes. Subject, Observer and Client. Subject, an object having methods to attach and de-attach observers to a client object. We've created classes Subject, Observer abstract class and concrete classes extending the abstract class the Observer.

ObserverPatternDemo, our demo class will use Subject and concrete class objects to show observer pattern in action.

Step 1
Create Subject class.
Subject.java
import java.util.ArrayList;
import java.util.List;
public class Subject {
   private List<Observer> observers 
      = new ArrayList<Observer>();
   private int state;

   public int getState() {
      return state;
   }

   public void setState(int state) {
      this.state = state;
      notifyAllObservers();
   }

   public void attach(Observer observer){
      observers.add(observer);
   }

   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   }
}

Step 2
Create Observer class.
Observer.java
public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}

Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{
   public BinaryObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Binary String: " 
      + Integer.toBinaryString( subject.getState() ) ); 
   }
}

OctalObserver.java
public class OctalObserver extends Observer{
   public OctalObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
     System.out.println( "Octal String: " 
     + Integer.toOctalString( subject.getState() ) ); 
   }
}

HexaObserver.java
public class HexaObserver extends Observer{
   public HexaObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Hex String: " 
      + Integer.toHexString( subject.getState() ).toUpperCase() ); 
   }
}

Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
   public static void main(String[] args) {
      Subject subject = new Subject();

      new HexaObserver(subject);
      new OctalObserver(subject);
      new BinaryObserver(subject);

      System.out.println("First state change: 15");
      subject.setState(15);
      System.out.println("Second state change: 10");
      subject.setState(10);
   }
}

Step 5
Verify the output:
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010

Is it helpful? Add Comment View Comments
 

Ques 2. What is builder pattern and give an example.

Builder pattern builds a complex object using simple objects and using a step by step approach. It creates one by one object and wraps on parent object. E.g. burger making, pizza making, house building etc.

Below we have created a Pizza restaurant where pizza and cold-drink is a typical meal. Pizza can be Italian, American, Mexican etc which will be packed in a wrapper and Cold-drink can be Pepsi, Coke, Limca etc which will be packed in a bottle.

Creating an Item interface representing food items such as pizzas and cold drinks and concrete classes implementing the Item interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as burger would be packed in wrapper and cold drink would be packed as bottle.

We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal object by combining Item. BuilderPatternDemo, our demo class will use MealBuilder to build a Meal.

Step 1
Create an interface Item representing food item and packing.
Item.java
public interface Item {
   public String name();
   public Packing packing();
   public float price();
}

Packing.java
public interface Packing {
   public String pack();
}

Step 2
Create concreate classes implementing the Packing interface.
Wrapper.java
public class Wrapper implements Packing {

   @Override
   public String pack() {
      return "Wrapper";
   }
}

Bottle.java
public class Bottle implements Packing {
   @Override
   public String pack() {
      return "Bottle";
   }
}

Step 3
Create abstract classes implementing the item interface providing default functionalities.
Pizza.java
public abstract class Pizza implements Item {

   @Override
   public Packing packing() {
      return new Wrapper();
   }
   @Override
   public abstract float price();
}

ColdDrink.java
public abstract class ColdDrink implements Item {
@Override
public Packing packing() {
       return new Bottle();
}
@Override
public abstract float price();
}

Step 4
Create concrete classes extending Pizza and ColdDrink classes
ItalianPizza.java
public class ItalianPizza extends Pizza {
   @Override
   public float price() {
      return 200.0f;
   }
   @Override
   public String name() {
      return "Italian Pizza";
   }
}

AmericanPizza.java
public class AmericanPizza extends Pizza {
   @Override
   public float price() {
      return 300.0f;
   }
   @Override
   public String name() {
      return "American Pizza";
   }
}

Coke.java
public class Coke extends ColdDrink {
   @Override
   public float price() {
      return 30.0f;
   }
   @Override
   public String name() {
      return "Coke";
   }
}

Pepsi.java
public class Pepsi extends ColdDrink {
   @Override
   public float price() {
      return 40.0f;
   }
   @Override
   public String name() {
      return "Pepsi";
   }
}

Step 5
Create a Meal class having Item objects defined above.
Meal.java
import java.util.ArrayList;
import java.util.List;
public class Meal {
   private List<Item> items = new ArrayList<Item>();
   public void addItem(Item item){
      items.add(item);
   }
   public float getCost(){
      float cost = 0.0f;
      for (Item item : items) {
         cost += item.price();
      }
      return cost;
   }
   public void showItems(){
      for (Item item : items) {
         System.out.print("Item : "+item.name());
         System.out.print(", Packing : "+item.packing().pack());
         System.out.println(", Price : "+item.price());
      }
   }
}

Step 6
Create a MealBuilder class, the actual builder class responsible to create Meal objects.
MealBuilder.java
public class MealBuilder {
   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ItalianPizza());
      meal.addItem(new Coke());
      return meal;
   }   
   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new AmericanPizza());
      meal.addItem(new Pepsi());
      return meal;
   }
}

Step 7
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
BuilderPatternDemo.java
public class BuilderPatternDemo {
   public static void main(String[] args) {
      MealBuilder mealBuilder = new MealBuilder();
      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " +vegMeal.getCost());
      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("nnNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " +nonVegMeal.getCost());
   }
}

Step 8
Verify the output.
Veg Meal
Item : Italian Pizza, Packing : Wrapper, Price : 200.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 230.0

Non-Veg Meal
Item : American Pizza, Packing : Wrapper, Price : 300.0
Item : Pepsi, Packing : Bottle, Price : 40.0
Total Cost: 340.0

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