Java Patterns Interview Questions and Answers

Creational Design Patterns

Q1. Define creational design patterns?
A. Creational patterns are used to define and describe how objects are created at class instantiation time. Usually an abstract super class contains the details of the classes that are instantiated and the client class is unaware of such details. Singletion pattern, factory method pattern, abstract factory pattern are examples of creational design pattern.

Q2. A class instance can be created using new operator. Why should we use creational design patterns to create objects?
A. Using new operator to create objects is a valid approach but it’s like hard coding the object type. If we are 100% sure that our object will be of the same class all the time, then we use new operator to create an object. In scenarios where the nature of the object can change according to the nature of the program, we use creational design patterns which offer flexible approach for creating class instances.

Q3. Which object oriented method is used by the creational patterns to instantiate object?
A. Creational patterns use inheritance to decide the object to be instantiated.

Q4. Define a factory with respect to software development.
A. Object construction is referred as a factory. It is used to isolate the creation of objects from their usage. If you are using factory methods for objects creation, then the new derived types will cause no code change in your classes that are using factories.

Q5. When will you use a Factory Pattern?
A. The factory pattern is preferred in the following cases: - a class does not know which class of objects it must create - factory pattern can be used where we need to create an object of any one of sub-classes depending on the data provided

Q6. Give an example of factory method that creates and return an object based on a String parameter. You have following interface. Create 2 implementations for it and write a factory method for it.

  1. package factory.pattern;
  2. public interface IMessage {
  3.      void sendMessage(String phNr, String messageContent);
  4. }
A. SMSMessage and MMSMessage are implementing IMessage and MessageFactory class provides a factory method getMessageSender(String arg) method.
  1. package factory.pattern;
  2. public class SMSMessage implements IMessage{
  3.         @Override
  4.         public void sendMessage(String phNr, String messageContent) {                System.out.println(String.format("Sending SMS contnet: %s to %s", messageContent, phNr));
  5.         }
  6. }
  7. package factory.pattern;
  8. public class MMSMessage implements IMessage{
  9.         @Override
  10.         public void sendMessage(String phNr, String messageContent) {
  11.                 System.out.println(String.format("Sending MMS contnet: %s to %s", messageContent, phNr));        }
  12. }
  13. package factory.pattern;
  14. public class MessageFactory {
  15.         public static IMessage getMessageSender (String arg){
  16.                 IMessage message = null;
  17.                 if(arg != null){
  18.                         if(arg.equals("SMS")){
  19.                                 message = new SMSMessage();
  20.                         } else if (arg.equals("MMS")){
  21.                                 message = new MMSMessage();
  22.                         }
  23.                 }
  24.                 return message;
  25.         }
  26. }

Q7. Given below is a class that provides a static factory method. Write a class to use this factory method.

  1. package factory.pattern;
  2. public class MessageFactory {
  3.         public static IMessage getMessageSender (String arg){
  4.                 IMessage message = null;
  5.                 if(arg != null){
  6.                         if(arg.equals("SMS")){
  7.                                 message = new SMSMessage();
  8.                         } else if (arg.equals("MMS")){
  9.                                 message = new MMSMessage();
  10.                         }
  11.                 }
  12.                 return message;
  13.         }
  14. }
  15. // IMessage interface - it can have many implementations
  16. package factory.pattern;
  17. public interface IMessage {
  18.         void sendMessage(String phNr, String messageContent);
  19. }
A. Based on the command line argument, factroy method will return an implementation of IMessage.
  1. package factory.pattern;
  2. public class MainTestClass {
  3.         public static void main(String[] args) {
  4.                 IMessage messageSender = MessageFactory.getMessageSender(args[0]);
  5.                 if(messageSender !=null){
  6.                         messageSender.sendMessage("1234", "Hello World");
  7.                 }
  8.         }
  9. }

Q8. Name the creational design pattern that provides abstraction one level higher than the factory pattern.
A. Abstract factory pattern provides abstraction one level higher than factory pattern. It encapsulates a group of individual factories.

Q9. Write example of abstract factory pattern using following interfaces.

  1. interface GUIFactory {
  2.     public Button createButton();
  3. }
  4. interface Button {
  5.     public void paint();
  6. }
A. WInFactory and OSXFactory are the implementations of GUIFactory. TestApplicationRunner provides createOsSpecificFactory method that returns GUIFactory.
  1. class WinFactory implements GUIFactory {
  2.    public WinButton createButton() {
  3.         return new WinButton();
  4.     }
  5. }
  6. class OSXFactory implements GUIFactory {
  7.     public OSXButton createButton() {
  8.         return new OSXButton();
  9.     }
  10. }
  11. class WinButton implements Button {
  12.     public void paint() {
  13.         System.out.println("I'm a WinButton");
  14.     }
  15. }
  16. class OSXButton implements Button {
  17.     public void paint() {
  18.         System.out.println("I'm an OSXButton");
  19.     }
  20. }
  21. class Application {
  22.     public Application(GUIFactory factory) {
  23.         Button button = factory.createButton();
  24.         button.paint();
  25.     }
  26. }
  27. public class TestApplicationRunner {
  28.     public static void main(String[] args) {
  29.         new Application(createOsSpecificFactory(args[0]));
  30.     }
  31.     public static GUIFactory createOsSpecificFactory(String arg) {
  32.         if (arg.equals("0)) {
  33.            return new WinFactory();
  34.        } else {
  35.            return new OSXFactory();
  36.        }
  37.    }
  38. }

Q10. What is the difference between factory design pattern and abstract factory design pattern?
A. Both are creational design patterns. Factory pattern is said to be there if there is method in a class that is used to create class instances. Any class can have factory methods. Using abstract factory pattern, an instance of a class is created that has only factory methods.

Q11. When will you use Abstract factory pattern?
A. Abstract factory pattern is preferred in situations where the names of actual implementing classes are not needed to be known at the client side. This would mean that we can change the implementation from one factory to another.

Q12. Which of the following relation can hold between abstract factory and factory method?

A. Abstract factory HAS_A (not always) factory method.

Q13. What benefits you achieve with factory method?
A. Factory method makes the code more flexible and reusable by eliminating the instantiation of application-specific classes. This way the code deals only with the interface and can work with any concrete class that supports this interface.

Q14. What is the liability of using factory method for object creation?
A. We need to do subclassing just to instantiate a particular class.

Q15. Name the design pattern in which a class delegates the responsibility of object instantiation to another object via composition.
A. Abstract factory pattern

Q16. Name the design pattern that uses inheritance and relies on a subclass to handle the desired object instantiation.
A. Factory method pattern Note: From Q to Q are base on the following code:

  1. public class MazeFactory {
  2. public Maze makeMaze() {return new Maze();}
  3. public Room makeRoom(int n) {return new Room(n);}
  4. public Wall makeWall() {return new Wall();}
  5. public Door makeDoor(Room r1, Room r2) {
  6. return new Door(r1, r2);}
  7. }
  8. public class EnchantedMazeFactory extends MazeFactory {
  9. public Room makeRoom(int n) {return new EnchantedRoom(n);}
  10. public Wall makeWall() {return new EnchantedWall();}
  11. public Door makeDoor(Room r1, Room r2)
  12. {return new EnchantedDoor(r1, r2);}
  13. }

Q17. What type of methods are defined in MazeFactory class?
A. MazeFactory class contains a collection of factory methods.

Q18. Name the AbstractFactory in the given code.
A. MazeFactory is acting as both an AbstractFactory and a ConcreteFactory.

Q19. Which design pattern you will use if your system being developed must use just one of a set of families of products?
A. Abstract factory pattern can be used if system being developed must use just one of a set of families of products.

Q20. What is singletion design pattern?
A. Singleton design pattern allows us to use just one instance of a particular class. It insures that one and only once instance of a particular class is used when requested.

Q21. Give an example scenario where you will use singletion pattern.
A. Assume what we are writing an application that needs to log events in a log file. Logging is done with timestamp. We do not want to have more than one instances of Logger otherwise the log file will be created with every instance. In this case, we use Singleton pattern and instantiate the logger when the first request comes or when the server is started.

Q22. Write singleton example?
A. The following class shows how to write a singleton class:

  1. public class SingletonObjectTest {
  2.         private static SingletonObject singletonObject;
  3.         private SingletonObjectTest() {
  4.         }
  5.         public static SingletonObjectTest getSingletonObject() {
  6.                 if (singletonObject == null) {
  7.                         singletonObject = new SingletonObjectTest();
  8.                 }
  9.                 return singletonObject;
  10.         }
  11. }

Q23. Can you name some design patterns that make use of singletion pattern?
A. The Abstract Factory, Builder, and Prototype patterns may use singletion pattern. Also facade objects are often singletons.

Q24. How to you prevent instantiation of a singletion class from other classes?
A. Singleton class can have a private constructor with zero argument to prevent instantiation from other classes. For example:

  1. public class SingletonTest {
  2. private SingletonTest() { }
  3. }

Q25. What are the drawbacks of using singletion design pattern?
A. The following drawbacks of Singleton pattern must be considered before applying it to any solution: - it introduces global state into an application and thus it makes unit testing far more difficult -access to the singleton in a multi-threaded context must be serialized

Q26. Name the creational design pattern that is used to build complex objects step by step.
A. Builder pattern builds complex objects from simple ones. It separates the construction of complex objects from their representation. The purpose of builder pattern is to abstract steps of object construction so that different implementations of these steps can construct different representations of objects.

Q27. What is the role of director in builder pattern implementation?
A. The sequence of object creation is managed by director class. It receives a Concrete Builder (implementation of abstract interface for creating objects) as a parameter and executes the necessary operations on it.

Q28. Write an example to show how builder pattern can be applied.
A. The following example uses builder pattern to construct a Pizza object using PizzaBuilder.

  1. public class Pizza {
  2.         private String dough;
  3.         private String sauce;
  4.         private String topping;
  5.         public String getDough() {
  6.                 return dough;
  7.         }
  8.         public void setDough(String dough) {
  9.                 this.dough = dough;
  10.         }
  11.         public String getSauce() {
  12.                 return sauce;
  13.         }
  14.         public void setSauce(String sauce) {
  15.                 this.sauce = sauce;
  16.         }
  17.         public String getTopping() {
  18.                 return topping;
  19.         }
  20.         public void setTopping(String topping) {
  21.                 this.topping = topping;
  22.         }
  23.         Pizza(PizzaBuilder builder) {
  24.                 dough = builder.getDough();
  25.                 sauce = builder.getSauce();
  26.                 topping = builder.getTopping();
  27.         }
  28.         @Override
  29.         public String toString() {
  30.                 return "Dough:"+dough +" Topping:"+topping+" Sauce:"+sauce;
  31.         }
  32. }
  33. public class PizzaBuilder {
  34.         String dough;
  35.         String sauce;
  36.         String topping;
  37.         public String getDough() {
  38.                 return dough;
  39.         }
  40.         public String getSauce() {
  41.                 return sauce;
  42.         }
  43.         public String getTopping() {
  44.                 return topping;
  45.         }
  46.         public PizzaBuilder setDough(String dough) {
  47.                 this.dough = dough;
  48.                 return this;
  49.         }
  50.         public PizzaBuilder setSauce(String sauce) {
  51.                 this.sauce = sauce;
  52.                 return this;
  53.         }
  54.         public PizzaBuilder setTopping(String topping) {
  55.                 this.topping = topping;
  56.                 return this;
  57.         }
  58.         public Pizza build() {
  59.                 return new Pizza(this);
  60.         }
  61. }
  62. public class PizzaBuilderExample {
  63.         public static void main(String[] args) {
  64.                 PizzaBuilder hawaiianPizzaBuilder = new PizzaBuilder()
  65.                                 .setDough("cross").setTopping("ham+pineapple").setSauce("mild");
  66.                 Pizza hawaiianPizza =;
  67.                 System.out.println("Hawaiian Pizza: "+hawaiianPizza);
  68.         }
  69. }

Q29. When cloning an object is preferred over creating a new one?
A. If cost of creating a new object is larger than the cost of cloning the object, then it is better to clone the object.

Q30. What is prototype pattern?
A. Prototype simply means making a clone and it is used to cloning an object to avoid its creation. Java provides an interface called Cloneable whose method clone() is used to clone an object.

Java Patterns User Questions     Java Patterns User Discussion