Design Pattern Interview Questions:
Define Creational design patterns?
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.
Singleton pattern, Factory pattern, Abstract Factory pattern are examples of creational design pattern.
A class instance can be created using new operator. Why should we use creational design patterns to create objects?
Using new operator to create objects is a valid approach but its 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.
Which object oriented method is used by the creational patterns to instantiate object?
Creational patterns use inheritance to decide the object to be instantiated.
Define a factory with respect to software development.
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.
When will you use a Factory Pattern?
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.
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.
Example:
package factory.pattern;
public interface IMessage {
void sendMessage(String phNr, String messageContent);
}
SMSMessage and MMSMessage are implementing IMessage and MessageFactory class provides a factory method getMessageSender (String arg) method.
package factory.pattern;
public class SMSMessage implements IMessage{
@Override
public void sendMessage(String phNr, String messageContent) { System.out.println(String.format("Sending SMS contnet: %s to %s", messageContent, phNr));
}
}
package factory.pattern;
public class MMSMessage implements IMessage{
@Override
public void sendMessage(String phNr, String messageContent) {
System.out.println(String.format("Sending MMS contnet: %s to %s", messageContent, phNr)); }
}
package factory.pattern;
public class MessageFactory {
public static IMessage getMessageSender (String arg){
IMessage message = null;
if(arg != null){
if(arg.equals("SMS")){
message = new SMSMessage();
} else if (arg.equals("MMS")){
message = new MMSMessage();
}
}
return message;
}
}
Given below is a class that provides a static factory method. Write a class to use this factory method.
Example
package factory.pattern;
public class MessageFactory {
public static IMessage getMessageSender (String arg){
IMessage message = null;
if(arg != null){
if(arg.equals("SMS")){
message = new SMSMessage();
} else if (arg.equals("MMS")){
message = new MMSMessage();
}
}
return message;
}
}
// IMessage interface - it can have many implementations
package factory.pattern;
public interface IMessage {
void sendMessage(String phNr, String messageContent);
}
Based on the command line argument, factory method will return an implementation of IMessage.
package factory.pattern;
public class MainTestClass {
public static void main(String[] args) {
IMessage messageSender = MessageFactory.getMessageSender(args[0]);
if(messageSender !=null){
messageSender.sendMessage("1234", "Hello World");
}
}
}
Name the creational design pattern that provides abstraction one level higher than the factory pattern.
Abstract factory pattern provides abstraction one level higher than factory pattern. It encapsulates a group of individual factories.
Write example of abstract factory pattern using following interfaces.
public interface GUIFactory {
public Button createButton();
}
interface Button {
public void paint();
}
WInFactory and OSXFactory are the implementations of GUIFactory. TestApplicationRunner provides createOsSpecificFactory method that returns GUIFactory.
class WinFactory implements GUIFactory {
public WinButton createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public OSXButton createButton() {
return new OSXButton();
}
}
class WinButton implements Button {
public void paint() {
System.out.println("I'm a WinButton");
}
}
class OSXButton implements Button {
public void paint() {
System.out.println("I'm an OSXButton");
}
}
class Application {
public Application(GUIFactory factory) {
Button button = factory.createButton();
button.paint();
}
}
public class TestApplicationRunner {
public static void main(String[] args) {
new Application(createOsSpecificFactory(args[0]));
}
public static GUIFactory createOsSpecificFactory(String arg) {
if (arg.equals("0)) {
return new WinFactory();
} else {
return new OSXFactory();
}
}
}
What is the difference between factory design pattern and abstract factory design pattern?
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.
When will you use Abstract factory pattern?
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.
Which of the following relation can hold between abstract factory and factory method?IS-AHAS_A
Abstract factory HAS_A (not always) factory method.
What benefits you achieve with factory method?
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.
What is the liability of using factory method for object creation?
We need to do subclassing just to instantiate a particular class.
Name the design pattern in which a class delegates the responsibility of object instantiation to another object via composition.
Abstract factory pattern
Name the design pattern that uses inheritance and relies on a subclass to handle the desired object instantiation.
Factory method pattern
Example
public class MazeFactory {
public Maze makeMaze() {return new Maze();}
public Room makeRoom(int n) {return new Room(n);}
public Wall makeWall() {return new Wall();}
public Door makeDoor(Room r1, Room r2) {
return new Door(r1, r2);}
}
public class EnchantedMazeFactory extends MazeFactory {
public Room makeRoom(int n) {return new EnchantedRoom(n);}
public Wall makeWall() {return new EnchantedWall();}
public Door makeDoor(Room r1, Room r2)
{
return new EnchantedDoor(r1, r2);}
}
What type of methods are defined in MazeFactory class?
MazeFactory class contains a collection of factory methods.
Name the AbstractFactory in the given code.
MazeFactory is acting as both an AbstractFactory and a ConcreteFactory.
Which design pattern you will use if your system being developed must use just one of a set of families of products?
Abstract factory pattern can be used if system being developed must use just one of a set of families of products.
What is singleton design pattern?
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.
Give an example scenario where you will use singleton pattern.
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.
Write singleton example?
The following class shows how to write a singleton class:
public class SingletonObjectTest {
private static SingletonObject singletonObject;
private SingletonObjectTest() {
}
public static SingletonObjectTest getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonObjectTest();
}
return singletonObject;
}
}
Can you name some design patterns that make use of singleton pattern?
The Abstract Factory, Builder, and Prototype patterns may use singleton pattern. Also facade objects are often singletons.
How to you prevent instantiation of a singleton class from other classes?
Singleton class can have a private constructor with zero argument to prevent instantiation from other classes. For example:
public class SingletonTest {
private SingletonTest() { }
}
What are the drawbacks of using singleton design pattern?
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.
Name the creational design pattern that is used to build complex objects step by step.
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.
What is the role of director in builder pattern implementation?
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.
Write an example to show how builder pattern can be applied.
The following example uses builder pattern to construct a Pizza object using PizzaBuilder.
public class Pizza {
private String dough;
private String sauce;
private String topping;
public String getDough() {
return dough;
}
public void setDough(String dough) {
this.dough = dough;
}
public String getSauce() {
return sauce;
}
public void setSauce(String sauce) {
this.sauce = sauce;
}
public String getTopping() {
return topping;
}
public void setTopping(String topping) {
this.topping = topping;
}
Pizza(PizzaBuilder builder) {
dough = builder.getDough();
sauce = builder.getSauce();
topping = builder.getTopping();
}
@Override
public String toString() {
return "Dough:"+dough +" Topping:"+topping+" Sauce:"+sauce;
}
}
public class PizzaBuilder {
String dough;
String sauce;
String topping;
public String getDough() {
return dough;
}
public String getSauce() {
return sauce;
}
public String getTopping() {
return topping;
}
public PizzaBuilder setDough(String dough) {
this.dough = dough;
return this;
}
public PizzaBuilder setSauce(String sauce) {
this.sauce = sauce;
return this;
}
public PizzaBuilder setTopping(String topping) {
this.topping = topping;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
public class PizzaBuilderExample {
public static void main(String[] args) {
PizzaBuilder hawaiianPizzaBuilder = new PizzaBuilder()
.setDough("cross").setTopping("ham+pineapple").setSauce("mild");
Pizza hawaiianPizza = hawaiianPizzaBuilder.build();
System.out.println("Hawaiian Pizza: "+hawaiianPizza);
}
}
When cloning an object is preferred over creating a new one?
If cost of creating a new object is larger than the cost of cloning the object, then it is better to clone the object.
What is Prototype pattern?
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.