Interview Questions on Design Patterns


1) Explain what is Java Design Pattern?

A design pattern is a language independent strategy for solving common object-oriented design problem. It describes how to structure classes to meet a given requirement.

2) Explain the advantages of Java design pattern?

  • The Design Patterns are reusable in multiple projects.
  • The Design Patterns provide a solution that helps to define the system architecture.
  • The Design Patterns capture software engineering experiences.
  • The Design Patterns provide transparency to the design of an application.
  • They are testified and well-proved since they have been built upon the knowledge and experience of expert software developers.

3) 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 Pattern in Software development.

These four authors are known as Gang of Four GOF.


4) What are the Creational Patterns?

Creational design patterns are related to the way of creating objects. Creational design patterns are used when a decision is made at the time of instantiation of a class.

  1. EmpRecord e1=new EmpRecord();

Since new keyword is used to create an object in Java, So, here we are creating the instance using the new keyword. In some cases, the nature of the object must be changed according to the nature of the program. In such cases, we should use the creational design patterns to provide a more general and flexible approach.


5) What Is Factory Pattern?

  • It is the most used design pattern in Java.
  • These design patterns belong to the Creational Pattern as this pattern provides one of the best ways to create an object.
  • In the Factory pattern, we don’t expose the creation logic to the client and refer the created object using a standard interface.
  • Factory Pattern allows the sub-classes to choose the type of objects to create.
  • The Factory Pattern is also known as Virtual Constructor.

6) What Is Abstract Factory Pattern?

Abstract Factory Pattern states that define an abstract class or interface for creating families of related objects but without specifying their concrete sub-classes. That means Abstract Factory allowed a class to return a factory of classes. That is why the Abstract Factory Pattern is one level higher than the Factory Pattern.

  • Abstract Factory patterns work around superclasses, which creates other classes.
  • The Abstract Factory Pattern comes under Creational Pattern as this pattern provides one of the best ways to create an object.
  • In the Abstract Factory pattern, an interface is liable for creating a factory of related objects without explicitly identifying their classes.
  • Each generated factory can give the objects according to the Factory pattern.

7) Explain Structural Patterns in Java?

Structural patterns are used to provide solutions and efficient standards regarding class compositions and object structures. They depend on the concept of inheritance and interfaces to allow multiple objects or classes to work together and form a single working whole.

Structural design patterns are responsible for how classes and objects can be composed to form larger structures.


8) Explain the Singleton pattern?

Singleton pattern in Java is a pattern which allows a single instance within an application. One good example of the singleton pattern is java.lang.Runtime.

Singleton Pattern states that define a class that has only one instance and provides a global point of access to it.

In other words, it is the responsibility of the class that only a single instance should be created, and all other classes can use a single object.


9) 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 instance at load time.

2. Lazy Instantiation

It is responsible for the creation of instance when required.


10) What are the Adapter patterns?

Adapter pattern converts the interface of a class into another interface based on the requirement.

In other words, it let you convert the interface according to requirement while using the class service with a different interface.

It is also known as Wrapper.

11) Illustrate the uses of Adapter Patterns?

It is used in the following cases:

  • When an object requires to utilize an existing class with an incompatible interface.
  • In case we want to create a reusable class that collaborates with classes which don’t have compatible interfaces.

12) Discuss the strategy to describe a design pattern?

The following points should need to be taken care to describe the design pattern.

  • The Pattern name and classification.
  • The Problem and solution.
  • Consequences: Variation and language-dependent alternatives should also be addressed.
  • Uses: Identify the uses in the real systems and its efficiency.

13) What is the decorator pattern in Java explain it with an example?

The decorator pattern is one of the popular Java design patterns. It is common because of its heavy usage in java.io (package). The Decorator Pattern uses composition in place of inheritance to extend the functionality of an object at runtime.

BufferedReader and BufferedWriter are some excellent examples of decorator pattern in Java.


14) Difference between Strategy and State design Pattern in Java?

This question is a commonly asked Java design pattern interview question as both Strategy and State pattern has the same structure. The UML class diagram of both patterns looks precisely the same, but their intent is different.

The state design pattern is used to manage and define the state of an object, while the Strategy pattern is used to describe a set of an interchangeable algorithm.


15) What are the advantages of Composite design Pattern in Java?

Composite design pattern allows clients to operate collectively on objects that may or may not represent a hierarchy of objects.

Advantage of composite design patterns is as follows.

  • It describes the class hierarchy that contains primitive and complex objects.
  • It makes it easy to add new kinds of the component.
  • It facilitates with the flexibility of structure with a manageable class or interface.

16) Can you describe the uses of the composite pattern?

It is used in the following cases:

  • When we want to represent a partial or full hierarchy of objects.
  • In case we need to add the responsibilities dynamically to the individual object without affecting other objects.

17) What are Some Design Patterns which are used in the JDK library?

Some of the design patterns which are used in the JDK library are as follows.

  • The decorator pattern is used by Wrapper classes.
  • Singleton pattern is used by Calendar classes (Runtime).
  • The Wrapper classes use factory pattern like Integer.valueOf.
  • Event handling frameworks use observer pattern like swing, awt.

18) Mention advantage of Builder design pattern in Java?

Advantages of builder design patterns are as follows.

  • It facilitates with a clear separation between the construction and representation of an object.
  • It provides improved control over the construction process.
  • The constructor parameter is reduced and is provided in highly readable method calls.
  • In design Pattern, the object is always instantiated in a complete state.
  • In the Builder design pattern, Immutable objects can be quickly built in the object building process.

19) Can you write Thread-safe Singleton in Java?

There are many ways to write a Thread-safe singleton in Java.

  • Thread-safe Singleton can be written by writing singleton using double-checked locking.
  • Another way is, by using static Singleton instance initialized during class loading.
  • By using Java enum to create a thread-safe singleton, this is the most straightforward way.

20) Is it possible to create a clone of a singleton object?

Yes, it is possible to create a clone of a singleton object.


21) What is the proxy pattern, and what does it do?

The term Proxy stands for an object representing another object. The proxy pattern provides a substitute or placeholder for another purpose to control access to it.

According to Gangs of four, a Proxy Pattern “provides control for accessing the original object.”

We can perform many security operations like hiding the information of the original object, on-demand loading, etc.

It is also called as placeholder or surrogates.


22) Explain some different type of proxies?

There are many cases where the proxy pattern is beneficial. Let’s have a look at some different proxies.

Protection proxy

It controls access to the real subject based on some condition.

Virtual proxies

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

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

Caching proxies

Caching proxies are 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

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

Smart proxies

Smart proxies are used to implement log calls and reference counting to the object.


23) Explain the Chain of Responsibility Pattern?

In the chain of responsibility pattern, Sender sends a request to a chain of objects, and any object in the chain can handle the request.

A Chain of Responsibility Pattern avoids coupling the sender of a request to its receiver. For example, an ATM service uses the Chain of Responsibility design pattern in monetary transactions.

Moreover, we can explain that usually, each receiver contains the reference of another receiver. If one object can fail to handle the request, then it sends the same to the next receiver and so on.


24) Explain the advantage of Chain of Responsibilities Pattern and when it is used?

  • It minimizes the coupling.
  • It provides flexibility while assigning the responsibilities to objects.
  • It permits a set of classes to act as one. The events produced in one class can be sent to other handler classes with the help of composition.

Usage of Chain of Responsibility Pattern

It is used in the following cases:

  • When more than one objects are ready to handle a request, and the handler is unknown.
  • In case the collection or a group of objects that can handle the request must be specified dynamically.

25) How is Bridge pattern is different from the Adapter pattern?

The motive of the Adapter pattern is to make interfaces of one or more classes to look similar.

The Bridge pattern is designed to isolate a class’s interface from its implementation so we can vary or substitute the implementation without changing the client code.


26) What’s the difference between the Dependency Injection and Service Locator patterns?

The service locator is used to create class dependencies. The Class is still responsible for creating its dependencies no matter whether if it is using service locator or not.

Service locators are also used to hide dependencies. We can’t say by looking at an object whether it connects with a database or not when it obtains connections from a locator.

With Dependency injection, the class which contains its dependencies neither knows nor cares where they came from.

One significant difference is that Dependency injection is much easier to unit test because we can pass in it mock implementations of its dependent objects. We could combine the two objects and apply the service locator.


27) What are the MVC patterns?

This pattern is one of the most-used patterns from J2EE Design pattern category. It is quite similar to the concept of Model-View-Controller. The abbreviation MVC is taken from the Model-view-controller concept.

Models are objects, used as blueprints for all of the objects that will be used in the application.

Views contain the presentational aspect of the data and information located in the models.

Controllers control both model and view as they serve as a connection between the two objects. The controller plays the role of an interface between View and Model and also intercepts all the incoming requests.


28) Explain the Intercepting Filter Design Pattern and also mention its benefits?

The intercepting filter design pattern is used to intercept and manipulate a request and response before and after the request processing. Filters perform the authentication/ authorization/ logging or tracking of request and then forward the requests to corresponding handlers. Let’s have a look at some basic entities of Intercepting design pattern.

Filter

It performs a certain task before or after the execution of request by request handler.

Filter Chain

It contains multiple filters and helps to execute them in defined order on target.

Target

The target object is the request handler

Filter Manager

It manages the filters and Filter Chain.

Client

The client object is one who sends a request to the Target object.

Benefits of Intercepting Filter Design Pattern

  • Filter pattern provides central control with loosely coupled handlers.
  • It expands reusability.
  • The new filter can be added at any time without affecting the client’s code.
  • Filters can be selected dynamically during program execution.

29) Explain Data Access Object (DAO) pattern?

Data Access Object Pattern is used to isolate low-level data accessing API or actions from high-level business services. Following are the components in the DAO Pattern.

Data Access Object Interface

DAO interface describes the standard actions to be performed on a model object(s).

Data Access Object concrete class

This class implements a DAO interface. This class is accountable to get data from a data source which can be Xml/database or any other storage mechanism.

Model Object or Value Object

This object is a plain old java object containing get/set methods to store data retrieved using DAO class.


30) Mention what is the difference between VO and JDO?

The difference between VO and JDO is that the JDO is a persistent technology that competes against entity beans. It allows to create POJO (plain old java objects) and persevere them to the database.

While VO (value objects) represents an abstract design pattern, that is used in conjunction with entity beans, JDBC and JDO.

 

31) Explain what is creational design patterns and Factory pattern?

Creational design pattern: This pattern is used to define and describe how objects are created at class instantiation time.

Factory pattern: The factory pattern is used to create an object without exposing the creation logic to the client and refer to a newly created object using a common interface.

32) Which design pattern is used to get a way to access the elements of a collection object in sequential manner?

Iterator pattern is used to get a way to access the elements of a collection object in sequential manner.

33) When service locator pattern is used?

When we want to locate various services using JNDI we use service locator pattern.

34) Mention in how many ways can you create singleton pattern?

To create single objects there are two famous ways

  • Lazy loading
  • Eager loading

35) Mention which pattern is used when we need to decouple an abstraction from its implementation?

When we want to decouple an abstraction from its implementation in order that two can vary independently we use bridge pattern.

36) Mention which design pattern will be helpful to add new functionality to an existing object?

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

37) Explain how can you create a Singleton class in Java?

It is two step process,

  • First make the constructor private so that new operator cannot be used to instantiate the class
  • Return an object of the object if not null otherwise create the object and return the same via a method.

38) Is it possible to write thread safe singleton in Java?

To write thread safe singleton in Java there are multiple ways for example by using static singleton instance initialized during class loading, by writing singleton using double checked locking. Java Enum is the simplest way to create thread safe singleton.

39) Mention how one should describe a design pattern?

To describe a design pattern, following things need to be taken care of

  • Pattern name and classification
  • Problem and solution
  • Consequences : Variation and language dependent alternatives should also be addressed
  • Know Uses: Identify the uses in the real systems and its efficiency

40) Mention why access to the non-static variable is not allowed from static method in Java?

You cannot access non-static data from static context because non-static variable are associated with a specific instance of an object while static is not associated with any instance.

41) Mention which pattern is useful when one has to pass data with multiple attributes in one shot from client to server?

Transfer Object Pattern is useful when one has to pass data with multiple attributes in one shot from client to the server.

42) Name some of the entities of DAO pattern?

Some of the entities of DAO include,

  • Data access object concrete class
  • Data access object interface
  • Model object or value object

43) Mention when can you use the Intercepting pattern?

Intercepting pattern is used when you have to do some pre-processing or post processing with request or response of the application.

44) Mention when to use a Factory Pattern?

Factory pattern can be used,

  • When a class does not know which class of objects needs to create
  • When class specifies its sub-classes to specify which objects to create
  • In programming language, you can use factory pattern where you have to create an object of any one of sub-classes depending on the given data

45) Explain in singleton pattern whether it is better to make the whole getinstance() method synchronized or just critical section is enough? Which one is preferable?

Synchronization of whole getinstance() method is costly and is only needed during the initialization on singleton instance, to stop creating another instance of Singleton. Therefore it is better to only synchronize critical section and not the whole method.

46) Mention in how many ways can you write singleton class in Java?

One can write singleton class in Java in four ways

  • Singleton with public static final field initialized during class loading
  • Singleton generated by static nested class, also referred as singleton holder pattern
  • Singleton by synchronizing get instance () method
  • From Java 5 on-wards using Enums

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

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

48) Mention what is the difference between “throw” and “throws”?

Keyword “Throw” is used to explicitly throw as an exception, while “Throws” is utilized to handle checked exceptions for re-intimating the compiler that exceptions are being handled. The throws need to be used in the method’s definition and also while invoking the method that raises checked exceptions.

49) Mention which classes in JDK uses singleton pattern?

Java.lang.Runtime classes uses singleton pattern in JDK.

50) Mention what is the limitation of using singleton pattern?

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

51)How to prevent cloning of a singleton object?

Throw exception with in the body of clone() method.

52)When to use the Strategy Design Pattern in Java?
Strategy pattern is quite useful for implementing a set of related algorithms like compression algorithms, filtering strategies, etc. The strategy design pattern allows you to create Context classes, which use Strategy implementation classes for applying business rules.

One good example of a Strategy pattern from JDK itself is a Collections.sort() method and the Comparator interface, which is a strategy interface and defines a strategy for comparing objects. Because of this pattern, we don’t need to modify the sort() method (closed for modification) to compare any object; at the same time, we can implement a Comparator interface to define a new comparing strategy (open for extension).

This pattern is actually based upon the open-closed design principle and if you understand that principle then its quite easy for you to understand the Strategy pattern as well. It’s actually better to know about SOLID principles as many design patterns are based upon that.

52)What is the Observer design pattern in Java? When do you use the Observer pattern in Java?
This is one of the most common Java design pattern interview questions. The observer pattern is based upon notification, there are two kinds of object Subject and Observer. Whenever there is a change in the subject’s state observer will receive a notification.

53)What is the difference between Strategy and State design Pattern in Java?
This is an interesting Java design pattern interview question as both Strategy and State pattern has the same structure. If you look at the UML class diagram for both patterns, they look exactly the same, but their intent is totally different.

The state design pattern is used to define and manage the state of an object, while the Strategy pattern is used to define a set of an interchangeable algorithm, and let’s client choose one of them. So Strategy Pattern is a client-driven pattern while Object can manage their state itself.

54)When to use the Composite design pattern in Java? Have you used it previously in your project?

This design pattern question is asked on Java interview not just to check familiarity with the Composite pattern but also, whether a candidate has the real-life experience or not.

The Composite pattern is also a core Java design pattern, which allows you to treat both whole and part object to treat similarly. Client code, which deals with a Composite or individual object, doesn’t differentiate between them, it is possible because the Composite class also implements the same interface as their individual part.

One of the good examples of the Composite pattern from JDK is the JPanel class, which is both Component and Container.  When the paint() method is called on JPanel, it internally called the paint() method of individual components and let them draw themselves.
In the second part of this design pattern interview question, be truthful; if you have used, then say yes, otherwise say that you are familiar with the concept and used it on your own.

55)Can you write thread-safe Singleton in Java?
There are multiple ways to write thread-safe Singleton in Java, like by writing singleton using double-checked locking, by using static Singleton instance initialized during class loading By the way, using Java enum to create thread-safe singleton is the most simple way

56)When to use the Template method design pattern in Java?
The Template pattern is another popular core Java design pattern interview question. I have seen it appear many times in real life project itself. The template pattern outlines an algorithm in the form of a template method and lets the subclass implement individual steps.

The critical point to mention, while answering this question, is that the template method should be final so that the subclass can not override and change the steps of the algorithm. Still, the same time individual steps should be abstract, so that child classes can implement them.

57)What is the difference between Decorator and Proxy pattern in Java?
Another tricky Java design pattern question and trick here is that both Decorator and Proxy implements the interface of the Object they decorate or encapsulate. As I said, many Java design patterns can have similar or exactly the same structure, but they differ in their intent.

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.

One more difference between Decorator and the Proxy design pattern is that the Decorator doesn’t create an object; instead, it gets the Object in its constructor, while Proxy actually creates objects.

58)When to use the Adapter pattern in Java? Have you used it before in your project?
Use the Adapter pattern when you need to make two class works with incompatible interfaces. Adapter pattern can also be used to encapsulate third party code so that your application only depends upon Adapter, which can adapt itself when third party code changes or you moved to a different third party library.

59)Can you give an example of  SOLID design principles in Java?
There are lots of SOLID design pattern which forms acronym SOLID like:
1. Single Responsibility Principle or SRP
3. Open Closed Design Principle or OCD
3. Liskov Substitution Principle
4. Interface Segregation Principle
5. Dependency Inversion Principle.

60)What is the difference between Abstraction and Encapsulation in Java?

Even though both Abstraction and Encapsulation look similar because both hide complexity and make the external interface simpler, there is a subtle difference between them. Abstraction hides logical complexity while Encapsulation hides Physical Complexity.

OOP Design Pattern Interview questions answers

61)Why Enum are best way to create singleton

1) Enum Singletons are easy to write

This is by far the biggest advantage if you have been writing Singletons prior ot Java 5 than you know that even with double-checked locking you can have more than one instance. though that issue is fixed with Java memory model improvement and guarantee provided by volatile variables from Java 5 onwards it still tricky to write for many beginners.

Compared to double-checked locking with synchronization Enum singletons are cake walk. If you don’t believe than just compare below code for conventional singleton with double checked locking and Enum Singletons:

2. Singleton using Enum in Java

This is the way we generally declare Enum Singleton, it may contain instace variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using an instance method then you need to ensure thread-safety of that method if at all it affects the state of an object.

By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.

/**
* Singleton pattern example using Java Enumj
*/

public enum EasySingleton{
INSTANCE;
}

You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.

3. Singleton example with double-checked locking

Below code is an example of double-checked locking in Singleton pattern, here getInstance() method checks two times to see whether INSTANCE is null or not and that’s why it’s called double-checked locking pattern, remember that double-checked locking is broker before Java 5 but with the guaranteed of volatile variable in java 5 memory model, it should work perfectly.

/**
* Singleton pattern example with Double-checked Locking
*/

public class DoubleCheckedLockingSingleton{
private volatile DoubleCheckedLockingSingleton INSTANCE;

private DoubleCheckedLockingSingleton(){}

public DoubleCheckedLockingSingleton getInstance(){
if(INSTANCE == null){
synchronized(DoubleCheckedLockingSingleton.class){
//double checking Singleton instance
if(INSTANCE == null){
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}

You can call DoubleCheckedLockingSingleton.getInstance() to get access of this Singleton class.

Now Just look at amount of code needed to create a lazy loaded thread-safe Singleton. With Enum Singleton pattern you can have that in one line because creation of Enum instance is thread-safe and guranteed by JVM.

People may argue that there are better way to write Singleton instead of Double checked locking approach but every approach has there own advantages and disadvantages like I mostly prefer static field Singleton initialized during classloading as shwon in below example, but keep in mind that is not a lazy-loaded Singleton:

Singleton pattern with a static factory method

This is one of my favorite method to impelemnt Singleton pattern in Java, Since Singleton instance is static and final variable it initialized when class is first loaded into memeory so creation of instance is inherently thread-safe.

/**
* Singleton pattern example with static factory method
*/

public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();

//to prevent creating another instance of Singleton
private Singleton(){}

public static Singleton getSingleton(){
return INSTANCE;
}
}

You can call Singleton.getSingleton() to get access of this class.

2) Enum Singletons handled Serialization by themselves

Another problem with conventional Singletons are that once you implement serializable interfacethey are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton as shwon in below example :

    //readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}

This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but witn Enum Singleton, Serialization is guarnateed by JVM.

3) Creation of Enum instance is thread-safe

As stated in point 1 since creatino of Enum instance is thread-safe by default you don’t need to worry about double checked locking.

In summary, given the Serialization and thraead-safety guaranteed and with couple of line of code enum, Singleton pattern is best way to create Singleton in Java 5 world. you can still use other popular methods if you feel so but I still have to find a convincing reason not to use Enum as Singleton, let me know if you got any.

 

62) When to use Builder Design pattern in Java

Builder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don’t confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.

That’s all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go.

 

Read more: https://javarevisited.blogspot.com/2012/06/builder-design-pattern-in-java-example.html#ixzz6mN6uCYyj

Popular posts from this blog

How to change column name in Dataframe and selection of few columns in Dataframe using Pyspark with example

What is Garbage collection in Spark and its impact and resolution

Window function in PySpark with Joins example using 2 Dataframes (inner join)