Design Patterns Interview Questions For Java
Published on

Design Patterns Interview Questions For Java

Authors

A design pattern provides a general reusable solution for the common problems in software design. Typically shows relationships and interactions between classes or objects. The idea is to speed up the development process by providing well-tested, proven development/design paradigms. Design patterns are programming independent language strategies for solving a common problem. That means a design pattern represents an idea, not a particular implementation. As a result, you can make your code more flexible, reusable, and maintainable by using it.

Table of Contents

Design Patterns

Mention the categories of Design Patterns in Java?

  • Creational Patterns
  • Structural Patterns
  • Behavioral Patterns
  • J2EE Patterns

Explain the advantages of the Java design pattern?

  • Make code reusable in multiple projects.
  • Provides a solution that helps to define the system architecture.
  • Captures software engineering experiences.
  • Provides transparency to the design of an application.
  • They are testified and well-proven since they have been built upon the knowledge and experience of expert software developers.

What Is Gang of Four (GOF)?

In 1994, four authors Erich Gamma, Ralph Johnson, Richard Hel, and John Vlissides, published a book titled Design Patterns Elements of Reusable Object-Oriented Software. This book introduced the concept of Design Patterns in Software development.

These four authors are known as Gang of Four GOF.

J2EE Design Patterns

List out J2EE patterns?

  • MVC Pattern
  • Data Access Object pattern
  • Front controller pattern
  • Intercepting filter pattern
  • Transfer object pattern

Explain MVC pattern in Java?

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 controllers if its data changes.

View – View represents the visualization of the data that the model contains.

Controller – Controller acts on both model and view. It controls the data flow into the model object and updates the view whenever data changes. It keeps view and model separate.

Explain the DAO pattern in Java?

Data Access Object Pattern or DAO pattern is used to separate low-level data accessing API or operations from high-level business services.

Data Access Object Interface – This interface defines the standard operations to be performed on a model object(s).

Data Access Object concrete class – This class implements the DAO interface. This class is responsible for getting data from a data source which can be database / XML or any other storage mechanism.

Model Object or Value Object – This object is a simple POJO containing get/set methods to store data retrieved using DAO class.

Explain the Front Controller Pattern?

The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler.

Front Controller – Single handler for all kinds of requests coming to the application (either web-based/ desktop-based).

Dispatcher – Front Controller may use a dispatcher object to dispatch the request to the corresponding specific handler.

View – Views are the object for which the requests are made.

Explain about Intercepting Filter Design Pattern?

The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with a request or response of the application.

Filters can do the authentication/ authorization/ logging or tracking of requests and then pass the requests to corresponding handlers.

Filter – Filter which will perform certain tasks prior to or after execution of request by the request handler.
Filter Chain – Filter Chain carries multiple filters and helps to execute them in defined order on target.
Target – The target object is the request handler.
Filter Manager – Filter Manager manages the filters and Filter Chain.
Client – The Client is the object who sends requests to the Target object.

Explain about Transfer Object Design Pattern?

The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server.

Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. It does not have any behavior.

Business Service – Fills the Transfer Object with data.
Transfer Object – Simple POJO having methods to set/get attributes only.
Client – Either requests or sends the Transfer Object to Business Object.

Creational Design Patterns

Explain Creational design patterns?

Creational design patterns are concerned with the way of creating objects. These design patterns are used when a decision must be made at the time of instantiation of a class (i.e. creating an object of a class).

List out Creational patterns?

  • Factory method
  • Abstract factory
  • Builder
  • Prototype
  • Singleton
  • Object Pool

Describe in how many ways can you create a singleton pattern?

There are two ways of creating a Singleton pattern.

  1. Early Instantiation – It is responsible for the creation of instances at load time.
  2. Lazy Instantiation – It is responsible for the creation of instances when required.

Can you write Thread-safe Singleton in Java?

  • Thread-safe Singleton can be done by writing singleton using double-checked locking.

  • Another way is by using a static Singleton instance initialized during class loading.

  • By using Java enum to create a thread-safe singleton, this is the most straightforward way.

Explain about Factory Method Design Pattern?

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate.

What are the advantages of the Factory Method Design Pattern?

  • Factory Method Pattern allows the sub-classes to choose the type of objects to create.
  • It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. It will work with any class that implements that interface or that extends that abstract class.

Explain about Abstract Factory Design Pattern?

Abstract Factory patterns work around a super-factory, which creates other factories. This factory is also called the factory of factories.

Explain about Builder Design Pattern?

Builder pattern builds a complex object using simple objects and using a step-by-step approach.

A Builder class builds the final object step by step. This builder is independent of other objects.

Explain about Prototype Design Pattern?

Prototype pattern refers to creating duplicate objects while keeping performance in mind.

This pattern involves implementing a prototype interface that tells it to create a clone of the current object. This pattern is used when the creation of an object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, return its clone on the next request and update the database as and when needed, thus reducing database calls.

Same way Hibernate improves performance by using cache and delaying database calls.

Explain about Object Pool Pattern?

Object pool pattern is a design pattern that is used in situations where the cost of initializing a class instance is very high.

Basically, an object pool is a container that contains some amount of objects. The object pool manages the connections and provides a way to reuse and share them.

The same way Java uses String Pool so that it can save space and runtime.

Example code for Early Instantiation of Singleton in Java?

class A {
	private static A obj=new A();//Early, instance will be created at load time
	private A(){}
	public static A getA(){
		return obj;
	}
}

Example code for Late Instantiation of Singleton in Java?

class A{
	private static A obj;
	private A(){}
	public static A getA(){
		if (obj == null){
			synchronized(Singleton.class){
				if (obj == null){
					obj = new Singleton(); //instance will be created at request time
				}
			}
		}
		return obj;
	}
}

Implement Singleton with Double Check Locking in Java?

public class DclSingleton {
	private DclSingleton(){}
	private static volatile DclSingleton instance;

	public static DclSingleton getInstance() {
		if (instance == null) {
			synchronized (DclSingleton .class) {
				if (instance == null) {
					instance = new DclSingleton();
				}
			}
		}
		return instance;
	}
}

One thing to keep in mind with this pattern is that the field needs to be volatile to prevent cache incoherence issues.

Even though the double-checked locking can potentially speed things up, since it requires the volatile keyword to work properly, it’s not compatible with Java 1.4 and lower versions.

Implement Enum Singleton in Java?

This is considered to be the most concise and safe way to write a singleton.

public enum EnumSingleton {
    INSTANCE;
    // other methods...
}

Structural Design Patterns

Explain Structural design patterns?

Structural patterns explain how to assemble objects and classes into larger structures while keeping these structures flexible and efficient.

The structural design patterns simplify the structure by identifying the relationships.

These patterns focus on how the classes inherit from each other and how they are composed of different classes.

List out Structural patterns?

  • Adapter
  • Bridge
  • Filter
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

Explain Adapter Design patterns?

The adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under a structural pattern as this pattern combines the capability of two independent interfaces.

Explain about Bridge Design Pattern?

A bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently.

It is a structural design pattern that lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation—which can be developed independently of each other.

Explain Filter Design Pattern?

A filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and to chain them in a decoupled way through logical operations.

Explain about Composite Design Pattern?

A composite pattern is used where we need to treat a group of objects in a similar way as a single object. Composite pattern composes objects in terms of a tree structure to represent part as well as a whole hierarchy.

Explain about Decorator Design Pattern?

A decorator pattern allows a user to add new functionality to an existing object without altering its structure.

This pattern creates a decorator class that wraps the original class and provides additional functionality keeping class methods signature intact.

Explain about Facade Design Pattern?

The facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.

Explain about Flyweight Design Pattern?

Flyweight pattern is primarily used to reduce the number of objects created, decrease memory footprint, and increase performance.

Explain about Proxy Design Pattern?

In the proxy pattern, a class represents the functionality of another class.

Explain some different types of proxy patterns?

Protection proxy – It controls access to the real subject based on some conditions.

Virtual proxies – These are used to instantiate the expensive object. The proxy manages the lifetime of the real subject in the implementation.

It decides the need for instance creation and when to reuse it. Virtual proxies optimize performance.

Caching proxies – Used to cache expensive calls to the real subject. There are many caching strategies that the proxy can use.

Some of them are read-through, write-through, cache-aside, and time-based. The caching proxies are used for enhancing performance.

Remote proxies – Used in distributed object communication. The remote proxy causes execution on the remote object by invoking a local object method.

Smart proxies – Used to implement log calls and reference counting to the object.

Behavioral Design Patterns

Explain Behavioural design patterns?

Behavioral design patterns are design patterns that identify common communication patterns among objects. By doing so, these patterns increase flexibility in carrying out communication.

List out Behavioral patterns?

  • Interpreter
  • Template method pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Observer pattern
  • Specification pattern
  • State pattern
  • Strategy pattern
  • Visitor pattern

Explain about Interpreter Design Pattern?

Interpreter pattern provides a way to evaluate language grammar or expression. This pattern is used in SQL parsing, symbol processing engine, etc.

Explain about Template method Design Pattern?

In the Template pattern, an abstract class exposes a defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementation as per need, but the invocation is to be in the same way as defined by an abstract class.

Explain about Chain of responsibility Design Pattern?

The chain of responsibility pattern creates a chain of receiver objects for a request. This pattern decouples the sender and receiver of a request based on the type of request.

Explain about Command Design Pattern?

The command pattern is a data-driven design pattern. A request is wrapped under an object as a command and passed to the invoker object. Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object which executes the command.

Explain the Iterator Design pattern?

Iterator pattern is a very commonly used design pattern in all programming languages. This pattern is used to access the elements of a collection object in a sequential manner without any need to know its underlying representation.

The need to implement the Iterator interface arises while designing custom data structures.

The class that implements the Iterable interface appropriately, can be used in the enhanced For loop (for-each loop) in Java.

Explain the Observer Design pattern?

The observer pattern is used when there is a one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.

Explain the Specification Design pattern?

Business rules can be recombined by chaining the business rules together using boolean logic. The pattern is frequently used in the context of domain-driven design.

The specification pattern is a way of encapsulating domain rules in objects. After their creation, developers can test if the various domain objects are satisfied by the specifications.

The specifications can also be chained. That allows developers to test objects for compliance with any, or all, of the specifications in a list.

Explain the State Design pattern?

State pattern a class behavior changes based on its state. Objects represent various states and a context object whose behavior varies as its state object changes.

Explain the Strategy Design pattern?

A class behavior or its algorithm can be changed at run time. We create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

Explain the Visitor Design pattern?

We use a visitor class that changes the executing algorithm of an element class. By this way, execution algorithm of the element can vary as and when visitor varies.

As per the pattern, the element object has to accept the visitor object so that the visitor object handles the operation on the element object.

For example, think of a Shopping cart where we can add different types of items (Elements). When we click on the checkout button, it calculates the total amount to be paid. Now we can have the calculation logic in item classes or we can move out this logic to another class using the visitor pattern

Explain how can you prevent creating another instance of singleton using the clone() method?

The preferred way to prevent creating another instance of a singleton is by not implementing a Cloneable interface and if you do just throw an exception from the clone() method “not to create a clone of singleton class”.

Mention what is the limitation of using a singleton pattern?

The singleton pattern ensures that a class has only one instance and provides a global point of access to it. But at the same time, this becomes its limitation as in most classes in an application you will need to create multiple instances.

What is the difference between Decorator and Proxy patterns in Java?

The Decorator pattern is used to implement functionality on an already created object, while a Proxy pattern is used for controlling access to an object.

Object Oriented Principles

What are the SOLID Principles?

SOLID Principle is an acronym of 5 principles in Object-Oriented Design (OOD).

S – Single Responsibility Principle
O – Open Close Principle
L – Liskov Substitution Principle
I – Interface Segregation Principle
D – Dependency Inversion Principle

Describe the Single Responsibility Principle?

Single Responsibility (SRP) ensures that every module or class should be responsible for single functionality supported by the software system. In other words, every class should have one and the only reason to change it.

Describe the Open Close Principle?

Open-Closed Principle (OCP) states or ensures that class, component, or entity should be open for extension but close for modification.

In detail, We can extend any class via Interface, Inheritance. or Composition whenever it’s required instead of opening a class and modifying its code.

For example, suppose you have implemented functionality to calculate the area of the Rectangle and after some time you need to calculate the area of the Square, then, In this case, you

should not modify your original class code to add extra code for square. Instead, you should create one base class initially and now you should extend this base class by

your square class.

Explain Liskov Substitution Principle?

Liskov Substitution Principle (LSP) states that Objects in a program can be replaced by the instances of their subtypes without modifying the correctness of a program.

In other words, if A is a subtype of B then instances of B may be replaced by the instances of A without altering the program correctness.

Explain Interface Segregation Principle?

Interface Segregation Principle (ISP) states that use many client-specific interfaces instead of one general-purpose interface.

In other words, No client should be forced to implement other methods which it does not require. It means it’s better to create a separate interface and allow your classes to implement

multiple interfaces.

Explain the Dependency Inversion Principle?

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend on details (concrete implementation). Details should depend on abstractions.

Explain Dependency Injection?

Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation. This helps you to follow SOLID’s dependency inversion and single responsibility principles.

List different types of dependency injection?

  1. Constructor injection: the dependencies are provided through a class constructor.
  2. Setter injection: the client exposes a setter method that the injector uses to inject the dependency.
  3. Interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

List the different libraries that use DI (Dependency Injection)?

Libraries and Frameworks that implement DI

  • Spring (Java)
  • Google Guice (Java)
  • Dagger (Java and Android)

Benefits of using DI (Dependency Injection)?

  • Helps in Unit testing.
  • Boilerplate code is reduced, as initializing of dependencies is done by the injector component.
  • Extending the application becomes easier.
  • Helps to enable loose coupling, which is important in application programming.

Disadvantages of DI (Dependency Injection)?

  • It’s a bit complex to learn, and if overused, it can lead to management issues and other problems.
  • Many compile-time errors are pushed to run-time.
  • Dependency injection frameworks are implemented with reflection or dynamic programming. This can hinder the use of IDE automation, such as “find references”, “show call hierarchy” and safe refactoring.

Difference between DI (Dependency Injection) and Dependency Inversion?

  • Dependency Injection is an implementation technique for populating instance variables of a class.
  • Dependency Inversion is a general design guideline that recommends that classes only have direct relationships with high-level abstractions.

What is the difference between a static class and a singleton class in Java?

  • A static class can not be a top-level class and can not implement interfaces where a singleton class can.
  • All static class members are static, but it is not a requirement for a Singleton class.
  • A static class gets initialized when loaded, so a static class cannot be lazily loaded, where a singleton class can be lazily loaded.
  • A static class object is stored in a stack, whereas a singleton class object is stored in heap memory space.