Design patterns interview questions part 1/Design Patterns Interview Questions and Answers for Freshers & Experienced

What is Decorator pattern?

Decorator pattern allows a user to add new functionality to an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.

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

What does proxy pattern do?

Proxy pattern provides a surrogate or placeholder for another object to control access to it.

What is SOLID?

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.

When to use the Template method?

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.

Which are J2EE Design Patterns?

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

What is a command pattern?

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.

What is Chain of Responsibility?

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.

Mention what is the difference between VO and JDO?

The difference between JDO and VO is that the JDO is a persistent technology that compete against entity beans in enterprise application development. It enables you to create POJO (plain old java objects) and persist them to the database.

While VO stands for value objects represents an abstract design pattern used in conjuction with entity beans, jdbc and possibly even JDO to overcome commonly found isolation and transactional problems in enterprise apps.

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.

What is Object Pool?

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

Mention which classes in JDK uses singleton pattern?

Mention which classes in JDK uses singleton pattern?

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.

What specific problems builder pattern solves?

This pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns.

When the Object contains a lot of attributes. Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.

Difference between Factory and Strategy Design Pattern?

Factory is a creational design pattern whereas Strategy is behavioral design pattern. Factory revolves around the creation of object at runtime whereas Strategy or Policy revolves around the decision at runtime.

When will you prefer to 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

Can you write thread-safe Singleton in Java?

There are multiple ways to write thread-safe singleton in Java
<> 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 this is most simple way.

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.

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”.

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.

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.

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.

What is Adapter design pattern ? Give examples of adapter design pattern in Java?

These are left for your exercise, try finding out answers of these design pattern questions as part of your preparation.

Give example of decorator design pattern in Java ? Does it operate on object level or class level ?

Decorator pattern enhances capability of individual object. Java IO uses decorator pattern extensively and classical example is Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading and writing for improved performance.

What is observer design pattern in Java

Observer design pattern is based on communicating changes in state of object to observers so that they can take there action. Simple example is a weather system where change in weather must be reflected in Views to show to public. Here weather object is Subject while different views are Observers. Look on this article for complete example of Observer pattern in Java.

What is main benefit of using factory pattern ? Where do you use it?

Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you can later replace original implementation of Products or classes with more advanced and high performance implementation without any change on client layer. See my post on Factory pattern for more detailed explanation and benefits.

Can you name few design patterns used in standard JDK library?

Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and various other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and Observer pattern which is used in Swing and many event listener frameworks.

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.

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.

When service locator pattern is used?

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

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.

Do you think using a prototype design pattern is better than creating an instance using the new keyword? If so, why?

Under certain circumstances, such as space or performance limitations, object creation is too bulky and requires an excessive amount of resources, to the point where creating a whole new instance will affect performance. In these cases, using the prototype design pattern can provide more efficiency by cloning a similar object. In this case, yes, a prototype design pattern would work more advantageously.

Describe the singleton pattern and your top advantages and disadvantages associated with it.

Singleton pattern is a creational pattern that restricts the instance of a class to just one single instance that will be able to coordinate actions across the whole system. The singleton design pattern is advantageous as it can be used over and over without the need to recreate a new object for every request. This is a huge time- and space-saver.

However, the code becomes so tightly coupled that you can't make changes without affecting everything associated with it. It also doesn't support inheritance and can be easily broken.

How is the bridge pattern different from the adapter pattern?

The adapter and bridge patterns are very similar. They're both considered a form of encapsulation and facilitate more control over code changes without impacting the class structure. However, the main difference between the two is that using a bridge pattern separates the essential data from its implementation, while an adapter pattern allows incompatible classes to interface with each other without changing the source code.

For example, the memory card slot on a computer is the adapter that allows the memory card to interface with the computer. A bridge pattern can be represented through the example of a household light switch. The switch for the device can be in the form of a chain, a 2-position switch or a dimmer, but regardless of the form, the bridge pattern makes sure that the switch performs the task of turning the light on and off.

In your opinion, what are the advantages of the builder design pattern?

"In my experience, I've found the builder pattern to be advantageous in that it encapsulates the construction and representation coding in separate containers to enable the construction process to produce multiple representations.

Also, I enjoy the improved control it gives me over the process of creating an object by breaking it up into steps to make it seem less complex than it is. It also reduces the required parameters for increased simplicity and readability and allows for immutable objects to be built into the pattern quickly."

In what order would you describe a design pattern in its documentation?

The facets of a design pattern are documented as follows:

1. Pattern name and classification
2. Intent (the problem being addressed)
3. Motivation (how the problem will be solved)
4. Applicability (instances in which the pattern can be applied)
5. Structure (diagram of the pattern)
6. Participants (classes and objects and their responsibilities)
7. Collaborations (how participants will interact to achieve the goal)
8. Consequences (trade-offs of the pattern)
9. Implementation (identifies specific issues with language)
11. Sample (snippets of code instructing pattern implementation)
12. Uses (identifies real-world uses)
13. Related patterns

Differentiate factory and abstract factory design patterns.

The primary difference between them is as follows: a factory pattern is a method of creating a single object through inheritance, while an abstract factory pattern creates factory patterns, effectively producing families of related objects.

Describe the factory pattern.

The factory pattern is a creational design pattern that acts as a container for the creational logic, separating it from dependent code to allow specific subclasses to make changes to the extension without affecting the main API. This is a highly used pattern because it's one of the best methods of creating objects without revealing the proprietary creation logic while remaining accessible on a shared interface.

What are the different categories of design patterns?

The three categories of design patterns are creational patterns, which allow freedom to choose how to create objects while hiding the logic; structural patterns, which identify and simplify relationships between objects and use inheritance to give the objects additional functions; and behavioral patterns, which identify how the objects communicate with one another.

Design ATM Machine ?

We all use ATM (Automated Teller Machine) , Just think how will you design an ATM ? for designing financial system one must requirement is that they should work as expected in all situation. so no matter whether its power outage ATM should maintain correct state (transactions), think about locking, transaction, error condition, boundary condition etc. even if you not able to come up exact design but if you be able to point out non functional requirement, raise some question , think about boundary condition will be good progress.

When do you overload a method in Java and when do you override it?

Rather a simple question for experienced designer in Java. if you see different implementation of a class has different way of doing certain thing than overriding is the way to go while overloading is doing same thing but with different input. method signature varies in case of overloading but not in case of overriding in java.

Design a Vending Machine which can accept different coins, deliver different products?

This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question should be solve in 3 hours, at least a working version.

In how many ways can you create singleton pattern in Java?

Singleton objects can be created in two ways.

Lazy loading
Eager loading

When to use Singleton?

Use the Singleton when

<> There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.

<> when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code

What does singleton Design Pattern do ?

It ensures that a class has only one instance, and provides a global point of access to it.

What Are Disadvantages of Design Patterns?

<> Design Patterns do not lead to direct code reuse.
<> Design Patterns are deceptively simple.
<> Teams may suffer from patterns overload.
<> Integrating design patterns into a software development process is a human-intensive activity.

Explain the Single Responsibility Principle (SRP)?

Single responsibility is the concept of a Class doing one specific thing (responsibility) and not trying to do more than it should, which is also referred to as High Cohesion.

Classes don't often start out with Low Cohesion, but typically after several releases and different developers adding onto them, suddenly you'll notice that it became a monster or God class as some call it. So the class should be refactored.

What is Proxy pattern?

In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.

In proxy pattern, we create object having original object to interface its functionality to outer world.

What is Dependency Injection?

Dependency injection makes it easy to create loosely coupled components, which typically means that components consume functionality defined by interfaces without having any first-hand knowledge of which implementation classes are being used.

Dependency injection makes it easier to change the behavior of an application by changing the components that implement the interfaces that define application features. It also results in components that are easier to isolate for unit testing.

What is Design Patterns and why anyone should use them?

Design patterns are a well-described solution to the most commonly encountered problems which occur during software development.

Design pattern represents the best practices evolved over a period of time by experienced software developers. They promote reusability which leads to a more robust and maintainable code.

R4R Team
R4R provides Design Patterns Freshers questions and answers (Design Patterns Interview Questions and Answers) .The questions on website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,Design patterns interview questions part 1,Design Patterns Freshers & Experienced Interview Questions and Answers,Design Patterns Objetive choice questions and answers,Design Patterns Multiple choice questions and answers,Design Patterns objective, Design Patterns questions , Design Patterns answers,Design Patterns MCQs questions and answers Java, C ,C++, ASP, C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for Design Patterns fresher interview questions ,Design Patterns Experienced interview questions,Design Patterns fresher interview questions and answers ,Design Patterns Experienced interview questions and answers,tricky Design Patterns queries for interview pdf,complex Design Patterns for practice with answers,Design Patterns for practice with answers You can search job and get offer latters by studing .learn in easy ways .