Design Patterns Interview Questions

Do you have your Java Design Pattern interview scheduled in the coming days? Prepare in advance with these frequently asked J2EE Design Pattern interview questions and answers. These interview questions focus primarily on the concepts of Design pattern, GoF, various Design patterns- Singleton, Observer, Factory, Builder, which will demonstrate your knowledge to the potential employer. All these questions are answered by the top industry experts and proved to be more useful in cracking the Design Pattern interview.   

  • 4.6 Rating
  • 30 Question(s)
  • 25 Mins of Read
  • 3325 Reader(s)

Beginner

A design pattern is a solution to a commonly occurring problem in software design.

They are about providing elegant, reusable solutions to commonly encountered software development problems in a particular context.

They are divided into three main categories: creational, structural and behavioural and Java/ J2EE

  • Creational design patterns provide solutions to instantiate an object in the best possible way for specific situations. These patterns are mainly related to Object instantiation.
  • Structural design patterns are concerned with how classes and objects can be composed to form larger structures. These patterns focus on, how the classes inherit from each other and how they are composed of other classes. These patterns are mainly related to larger structures of classes or objects
  • Behavioural patterns are concerned with the assignment of responsibilities and communication between objects, or, encapsulating behaviour in an object and delegating requests to it. These patterns are mainly related to interaction and distribution of responsibility.
  • J2EE patterns are concerned with the presentation tier.

Eric Gamma, Richard Helm, Ralph Johnson and John Vlissides are four authors who came up with elements of reusable object-oriented software which initiated the concept of design-pattern in software development. They had introduced this concept in 1994 and published a book for the same.

The authors are collectively known as Gang of Four ( GOF ).

Creational design patterns are related to Object instantiation. The following design patterns are categorized under creational design patterns.

  • Factory: Factory methods helps us to create Objects without specifying the class. It provides an interface for creating objects in a superclass, but subclass can alter the type as well.
  • Abstract Factory: This pattern encapsulates a set of similar factories that produces the objects.
  • Builder: Need to specify type and data. Based on that this method encapsulates the construction of objects as per their representation.
  • Singleton: By implementing this method, the class makes sure that there are not more than one objects can be created by a particular class.
  • Prototype: This pattern is used to clone or copy the already initialized instance.

Structural design patterns are related to the larger structure of classes or objects. Here are some of the examples of structural design patterns.

  • Adapter: This provides a bridge for the incompatible interfaces. It acts as a wrapper for an existing interface.
  • Bridge: For extensible coding, a bridge pattern decouples the abstractions from implementation. You can think of defining two separate interfaces one for abstractions and one for implementation.
  • Composite: Compose objects in a tree structure to represent whole-part hierarchies.
  • Decorator: To extend functionality dynamically.
  • Facade: Encapsulate complex subsystem wrapped into a simpler one.
  • Flyweight: Sharing to support a large number of objects efficiently.
  • Private Class Data: Reduce exposure of attributes by limiting their visibility.
  • Proxy: Create real-time objects when required, meanwhile continue to use placeholder which acts as a proxy.

Behavioural design patterns are mainly dealing with the interaction between objects. Here are some of the examples of behavioural design patterns.

  • Chain of Responsibility: Method which controls the passing a request among a chain of objects.
  • Command: Encapsulate a command request in an Object. Hide all complexities behind a method like execute() and simplify interfaces.
  • Interpreter: Mapping a domain knowledge to a grammar. Interpreter understands the meaning behind it.
  • Mediator: An Object which encapsulates how a set of objects interact. It promotes loose coupling by removing the need for explicit reference.
  • Memento: To Restore an object back to its previous state without violating encapsulation.
  • Observer: To Scale, define one to many dependencies between objects. So all observers get notification of state change.
  • State: Alter the behaviour of an object when its state changes.
  • Strategy: Encapsulate a family of algorithms behind a class and make them interchangeable.
  • Template Method: Allow subclasses to redefine the superclass behaviour.
  • Visitor: Define a new operation on a class without changing it.

Antipatterns are counterparts to design patterns. By implementing a solution to a commonly occurring problem which generates negative consequences. This can be a result of a developer not knowing how best to apply a design pattern or applying with the wrong context. It presents a plan for reversing underlying causes and implementing product solutions.

While designing classes, sometimes we want the ability to restrict the creation of only one object for a particular class. Singleton pattern allows only one instance of a class to be created. On asking for a new object to be created, the class might return the pre-created object only and the same object is reused for the whole application. Advantage of the singleton pattern is that it saves memory. Whereas the disadvantage is that the code becomes tightly coupled as the singleton object acts as a global object. It doesn’t support inheritance and for some languages, the techniques like cloning, reflection and for distributed JVM applications the contract might break.

Though you can prevent some of the situations like for cloning, you can throw an exception in the clone() method.

Following are the differences between a static class and a class which has implemented the singleton pattern.

  • All members of a static class must be static Vs Singleton class does not have that requirement.
  • A Static class gets initialized when classes are getting loaded by class loader and thus they can’t be lazily initialized Vs Singleton classes can be loaded lazily.
  • The objects of static classes are stored on stack Vs the objects of singleton class are stored in heap memory space.
  • A static class can not be a top level class and cannot implement interfaces Vs Singleton class can

While designing applications, many times situation comes where we need to act when a certain object changes its state. This situation is generally referred to as publisher and subscriber theory as well. In this situation, all of the objects which have subscribed to the event of an object’s state change are automatically notified. This falls under the behavioural pattern category.

The Subscriber / Observer provides and method which will be called by the subject to notify it of the subject’s state change. The subscriber also provides methods like attach(), detach(), setstate() and notify().

When there is a need for creating a duplicate object while keeping performance in mind, we can use a prototype pattern. It involves implementing a prototype interface which tells to create a clone of the current object. We should use the prototype pattern when the object creation is costly. Every time Instead of creating a new object, we shall reuse specific objects which are pre-created. For example, an object is to be created after a costly database operation. We can cache the object for reuse and return the clone on next request and update the database.

The factory design pattern is probably the most used design pattern in programming languages. Factory pattern is a type of creational design pattern. It hides the implementation details of the instantiation of objects to the clients.

Instead of using new operator themselves client needs to ask factory classes to return objects which are required. The factory methods are responsible to instantiate a new object and return the same, and many times cast to the top of an abstract class.  

If you really require a factory to create objects, then only you should use it otherwise it can create complexities as well.

Here is an example class which returns

Public class Supervisor extends User{ … }
Public class Employee extends User{ … }
public class UserFactory{
public User createUser(String TypeId){
if (TypeId==1)
return new Supervisor();
if (TypeId==2) return
return new Employee();
... // so on for the other Ids

       return null; //if the id doesn't have any of the expected values
   }
   ...
}

When classes are more complex in nature and when a client needs to create an object, builder pattern comes to the rescue. A client only needs to provide type and data for the class for the object to be created. It provides a common interface through which the object can be created.

It uses a factory builder pattern to decide which concrete class to initiate in order to build the desired type of object. For example, if you want to build a car. There are many components to build a car. And based on the type of car, there can be many differences. So assume that an automobile manufacturer wants to build a car.

Public class CarManufacturer{
Private CarBuilder carBuilder;
Public CarManufacturer( CarBuilder carBuilder ){
this.carBuilder = carBuilder;
}
Public void constructCar(){
carBuilder.buildBase();
carBuilder.buildStructure();
carBuilder.buildRoof();
carBuilder.buildInterior();
}
}
class SuzukiBuilder implements CarBuilder{
Private Car car;
Public void buildBase(){
System.out.println(“Built Iron Base..”);
}
…
...
}
Interface carBuilder{
buildBase();
buildStructure();
buildRoof();
buildInterior();
}

An object pool is a creation pattern where, if the operation of creating an object is complex and time-consuming we can use Object Pool. A common application of Object Pool which applications use in general is with database connections.  On application initialization, it pre-creates a set of objects and keeps them alive in a collection. Whenever there is a need, the authoritative manager assigns one object to the client and allows it to use. Once used, the object’s is not being destroyed but returned to the pool. Periodically the validity of an object is being checked by routines. If the object is not reusable, it gets destroyed and again the authoritative pool manager decides to create new objects based on the configuration/requirement by the client.

One needs to take care of the following scenarios:

  • A limited number of resources in a pool
  • When new resource creation fails.
  • Synchronization
  • Expiry of resources

Chain of responsibility is a type of behavioural pattern. Whenever there is a situation where there are more than one object handles commands and the handler is not known in advance, the client is not aware of the handler in advance, and it is taken care automatically. And the request to be handled is handed over to a group of objects to process the request in a dynamic way.

Take an example of approval for an opening in a company. Once the manager has created a requirement of the opening/role, it needs to go through multiple hierarchies for approval from HR, Finance, Business etc. Approval from all departments if comes positive then only the overall approval status of the requirement is positive.

When we have to implement a scenario where a list of commands needs to get executed, or actions needs to be performed based on the input given by the client, we can implement a command pattern.

It acts like a macro, a command that is translated to a set of actions to be performed by a particular device/service.  It makes our code extensible and we can add new commands without changing the existing code. It also reduces the coupling of code.

For example, if there are two buttons of a remote ( On and Off ), we want to use the same two buttons on more than one items selected in the menu.  Like fan, Television, Tubelight. By selecting one of the items if we press On, it should send a command.

Public interface command{
Public void execute(){
}
}
Public Class Television{
Public void on(){ System.out.println(“TV is on”);  }
Public void off(){ System.out.println(“TV is off”);  }
}
Public class TVCommandHandler extends command{
Television tv;
Public turnOnTV(Television tv ){
This.tv = tv;
}
Public void execute(){
tv.on();
}
}

Similar way, we can add more appliances and we can add the same command and implement the same in the above manner.

Here is a list of J2EE Design patterns at various layers.

View Layer :

  • Front controller
  • Application Controller
  • Intercepting filter
  • Composite view
  • Context Object

Business Layer

  • Data transfer objects
  • Business delegate
  • Converter / Casting
  • Service Locator

Integration

  • Data Access Object
  • Service Activator

When the steps to solve an algorithm is fixed and if we can create a template of steps which subclass can implement based on their need, we can use template method design pattern.

In this pattern the template method itself should be final, so that subclass cannot override it and change the steps but if needed they can be made abstract so that the subclass can implement them based on the need.

SOLID  is an acronym used for the following design principles.

  • S: Single Responsibility principle - every module or a class should have the responsibility of a single part of the functionality and it should be entirely encapsulated by the same class or module.
  • O: Open Closed Principle - software entities should be open for extension and closed for modification.
  • L: Liskov Substitution Principle: is a concept in Object Oriented Programming that states, Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
  • I: Interface Segregation Principle: states that no client should be forced to depend on methods it does not use
  • D: Dependency Inversion Principle - High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.

Advanced

In the following example, we can show how to break singleton pattern implementation in Java. And how to prevent it.

           First_instance = ExampleSingletonClass.instance;
for (Constructor construct : ExampleSingletonClass.class.getDeclaredConstructors() )
           {
               constructor.setAccessible(true);
               second_instance = (ExampleSingletonClass) constructor.newInstance();
               break;
           }

As you can see in the example above, we got one instance and the second instance was created using reflection.

In order to prevent the same, you can use enums in java. As enum values are only instantiated once. Reflection can not clone this as the enums do not have constructors.

           Public enum ExampleSingletonClass{
INSTANCE;
}

Here is an example of how you can break a singleton pattern by serialization and create multiple objects of the same class.

 ----
ExampleSingletonClass first_instance = ExampleSingletonClass.instance;
           ObjectOutput out
               = new ObjectOutputStream(new FileOutputStream("file.text"));
           out.writeObject(first_instance);
           out.close();
           ObjectInput in
               = new ObjectInputStream(new FileInputStream("file.text"));
           ExampleSingletonClass  second_instance = (ExampleSingletonClass ) in.readObject();
           in.close();
-------

If you print the hashcode of both of the instances, you will realize that they are not the same.

If you want to prevent this situation then, you should implement the readResolve() method and return the same instance in that method.

Here is an example which shows how to break singleton pattern using cloning in java.

ExampleSingletonClass first_instance = ExampleSingletonClass.instance;

ExampleSingletonClass second_instance = (ExampleSingletonClass) instance1.clone();

In order to prevent the singleton pattern from breaking you have to override the method clone() which throws an exception CloneNotSupportedException and returns the same instance.

@Override
 protected Object clone() throws CloneNotSupportedException
  {
    return instance;
  }

When we have to implement a set of related algorithms the strategy pattern comes in to picture. It allows us to create contextual classes, which is further used by Classes which implement this strategy for applying custom business rules. It follows Open closed principle.

One of the favourite examples is the Collections.sort() method and Comparator interface. The interface defines the strategy to compare any object. If you have to provide a custom implementation for comparing a specific type of object then you can override the comparing strategy.

When an object is already created and we need to modify them on top then we have to use the decorator pattern. In Decorator pattern object is not created, but the object is passed as an argument to constructor.

In proxy design, pattern object is actually getting created, and it is mainly being used to control the access of an object.

Both Decorator and Proxy implement the interface of the object that they decorate or encapsulate. Both of them have the same structure but the intent is very different.

In order to decouple the business layer and presentation layer, the business delegate design pattern is used. Here are the associated list of components,

  • Client: UI Code ( Presentation layer )
  • Business Single entry point class for client entities to expose service methods.
  • business service: actual business logic encapsulated by the business service interface.
  • Lookup service: to provide business object access to business delegate, it is responsible to get the relative business implementation.

Many times it happens in the real world that one functionality might require data from multiple POJOs in the backend. Client needs to initiate multiple calls to receive all data. In those cases, one can create a POJO which is required by the functionality and on the server side, a server can aggregate data from multiple resources and create one POJO. Generally, that is called as a transfer object or a value object.

Transfer Object has only the data and the class has fields and getters and setters. Transfer object is filled up by the service methods and it fills the transfer object with the business object data.

A client doesn’t know different data types, so it can talk to the server by passing the transfer object and invoke the services required.

This pattern was mainly used in Enterprise Java Beans. It is a representation of a graph of objects. When a composite entity is getting updated, the dependent beans also gets updated. Here are some of the components of a composite entity pattern.

  • Composite entity: It is being used for persistence purpose.
  • Coarse-Grained Object: The object which contains dependent objects. It is also responsible to manage the life cycle of its own as well as dependent objects.
  • Dependent Object: This object is dependent on a coarse-grained object for its persistence life cycle.
  • Strategy: Strategy to implement composite entity.

DAO Stands for data access object pattern. It is used to separate the low-level data access API or operation from business logic.  Implementing this method helps us write code which is generic and non-dependent on specific venor of storage.

Here are some of the components or participants in the DAO Pattern.

  • DAO Interface: Operations to be performed on the modal object.
  • Implementation Concrete class: Implements DAO Interface and this class is responsible to implement methods which can fetch data from the actual storage mechanism.
  • Entity Object or Value Object: This object is being returned by the DAO on which operations like save() or retrieve() might be performed.

Memento is a behavioural pattern. In order to restore an Object’s state to a previous state, the memento design pattern is being used.

It uses three actor classes for its operations.

  • Memento: State of an object to be restored.
  • Originator: Creates and stores state in memento.
  • Caretaker: Can restore state from memento.

The front controller patterns act as a single point of contact for the client. It can handle all of the cross-cutting functions which are applied on every single request, for ex. Authentication, authorization, analytics, logging. Once the controller receives the request, it can then forward the request to process it further.  

There are three components involved.

  • Front controller: which handles all requests. Acts as an entry point and forwards the request to the appropriate controller.
  • Dispatcher: it has the config which can map a request to a handler so that the dispatcher can dispatch a request to a specific handler.
  • View: These are objects for which request has come.

Generally, we use to validate if the object is null or not. Many times it becomes our first line of validation for any kind of parameters. In this pattern, the check of the Null object instance is replaced by a null object. In this pattern, we create an abstract class which might contain operations to be done. A concrete class which extends the abstract class provide do nothing implementation of this class and will be used whenever we want to use to check against the null value.

Description

Design Patterns are very popular among software developers. It has a solution to any commonly occurring problem. Java in Design Pattern is widely used as a programming language in the software industry, no matter which role you will be playing in the organization.
  

According to Payscale, the average pay for a Software Engineer with Design Pattern (Computer Science) skills is $90,989 per year. Java with Design Pattern skill can play roles like a programmer, software engineer, senior software engineer in Java, Java J2EE Developer, Java Microservices Developer, Java Server Side Developer, etc. There are many companies that hire Java programmer with Design Pattern skilled professionals. Few of these companies include- Morgan Stanley, Vanguard, FutureSoft IT, PayPal, Verizon, JP Morgan Chase, etc.
 

In case you are preparing for the Java Design Patterns job interview and in skeptics that what level of questions will be asked in a job interview then these Design Pattern with Java interview questions and answers framed by the experts will help to get acquainted with the nature of the questions you may encounter during your J2EE Design Pattern job interview. These Design Patterns in Java Questions and Answers has been designed with a special intention of helping job seekers preparing for various job interviews.   
 

Below are the frequently asked Java Design Patterns interview questions and answers which makes you comfortable to face any type of interviews. So, be confident while facing your J2EE Design Pattern interview.
 

Wish you best of luck for your future endeavors. Cheers!

Read More
Levels