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

What Is Factory Pattern In Java? What Is Advantage Of Using Static Factory Method To Create Object?

Factory pattern used to create object by providing static factory methods. There are many advantage of providing factory methods e.g. caching immutable objects, easy to introduce new objects etc.

When To Use Composite Design Pattern In Java? Have You Used Previously In Your Project?

This design pattern question is asked on Java interview not just to check familiarity with Composite pattern but also, whether candidate has real life experience or not.
Composite pattern is also a core Java design pattern, which allows you to treat both whole and part object to treat in similar way.
Client code, which deals with Composite or individual object doesn't differentiate on them, it is possible because Composite class also implement same interface as there individual part.
One of the good example of Composite pattern from JDK is JPanel class, which is both Component and Container.
When paint() method is called on JPanel, it internally called paint() method of individual components and let them draw themselves.

Define A Factory With Respect To Software Development?

Object construction is referred as a factory.
It is used to isolate the creation of objects from their usage.
If you are using factory methods for objects creation, then the new derived types will cause no code change in your classes that are using factories.

Which Object Oriented Method Is Used By The Creational Patterns To Instantiate Object?

Creational patterns use inheritance to decide the object to be instantiated.

A Class Instance Can Be Created Using New Operator. Why Should We Use Creational Design Patterns To Create Objects?

1. Using new operator to create objects is a valid approach but it's like hard coding the object type.
2. If we are 100% sure that our object will be of the same class all the time, then we use new operator to create an object.
3. In scenarios where the nature of the object can change according to the nature of the program, we use creational design patterns which offer flexible approach for creating class instances.

Define A Factory With Respect To Software Development?

<> Object construction is referred as a factory.
<> It is used to isolate the creation of objects from their usage.
<> If you are using factory methods for objects creation, then the new derived types will cause no code change in your classes that are using factories.

Which Object Oriented Method Is Used By The Creational Patterns To Instantiate Object?

Creational patterns use inheritance to decide the object to be instantiated.

A Class Instance Can Be Created Using New Operator. Why Should We Use Creational Design Patterns To Create Objects?

<> Using new operator to create objects is a valid approach but it's like hard coding the object type.
<> If we are 100% sure that our object will be of the same class all the time, then we use new operator to create an object.
<> In scenarios where the nature of the object can change according to the nature of the program, we use creational design patterns which offer flexible approach for creating class instances.

Define Creational Design Patterns?

Creational patterns are used to define and describe how objects are created at class instantiation time.
Usually an abstract super class contains the details of the classes that are instantiated and the client class is unaware of such details.
Singletion pattern, factory method pattern, abstract factory pattern are examples of creational design pattern.

Give Example Of Decorator Design Pattern In Java ? Does It Operate On Object Level Or Class Level?

1. Decorator pattern enhances capability of individual object.
2. 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 Are The Entities Of Intercepting Filter Pattern?


Following are the entities of this type of design pattern:

Filter - Filter which will performs certain task prior or after execution of request by request handler.
Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target.
Target - Target object is the request handler.
Filter Manager - Filter Manager manages the filters and Filter Chain.
Client - Client is the object who sends request to the Target object.

What Is Intercepting Filter Pattern?

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

<> Filters are defined and applied on the request before passing the request to actual target application.
<> Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers.

What Is 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.

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

Following are the entities of this type of design pattern:

1. Front Controller - Single handler for all kinds of requests coming to the application eitherwebbased/desktopbased.
2. Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler.
3. View - Views are the object for which the requests are made.

What Is Data Access Object Patterndao Pattern?

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

Following are the participants in Data Access Object Pattern:

1. Data Access Object Interface - This interface defines the standard operations to be performed on a model objects.
2. Data Access Object concrete class - This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism.
3. Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

What Is Business Delegate Pattern?

Business Delegate Pattern is used to decouple presentation tier and business tier:

It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code.

In business tier we have following entities:

<> Client - Presentation tier code may be JSP, servlet or UI java code.
<> Business Delegate - A single entry point class for client entities to provide access to Business Service methods.
<> LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object.
<> Business Service - Business Service interface. Concrete classes implement this business service to provide actual business implementation logic.

What Is Visitor Pattern?


1. In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class.
2. By this way, execution algorithm of element can vary as and when visitor varies.
3. This pattern comes under behavior pattern category.
4. As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the element object.

What Is Strategy Pattern?


1. In Strategy pattern, a class behavior or its algorithm can be changed at run time.
2. This type of design pattern comes under behavior pattern.
3. In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.
4. The strategy object changes the executing algorithm of the context object.

What Is Null Object Pattern?

In Null Object pattern, a null object replaces check of NULL object instance.
Instead of putting if check for a null value, Null Object reflects a do nothing relationship.
Such Null object can also be used to provide default behaviour in case data is not available.
In Null Object pattern, we create an abstract class specifying various operations to be done, concrete classes extending this class and a null object class providing do nothing implemention of this class and will be used seemlessly where we need to check null value.

What Is Observer Pattern?


1. Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically.
2. Observer pattern falls under behavioral pattern category.

Name The Actor Classes Used In Memento Pattern?

1. Memento pattern uses three actor classes.
2. Memento contains state of an object to be restored.
3. Originator creates and stores states in Memento objects and Caretaker object is responsible to restore object state from Memento.

What Is Mediator Pattern?

1. Mediator pattern is used to reduce communication complexity between multiple objects or classes.
2. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling.
3. Mediator pattern falls under behavioral pattern category.

What Are The Entities Of Service Locator Pattern?

Following are the entities of this type of design pattern:

1. Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server.
2. Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose.
3. Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services.
4. Cache - Cache to store references of services to reuse them.
5. Client - Client is the object that invokes the services via ServiceLocator.

Give An Example Where Interpreter Pattern Is Used?

This pattern is used in SQL parsing, symbol processing engine etc.

What Is Flyweight Pattern?

1. Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance.
2. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application.
3. Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object when no matching object is found.

What Is Composite Pattern?

1. Composite pattern is used where we need to treat a group of objects in similar way as a single object.
2. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy.
3. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects.
4. This pattern creates a class that contains group of its own objects.
5. This class provides ways to modify its group of same objects.

When Prototype Pattern Is To Be Used?

1. This pattern is used when creation of object directly is costly.
2. For example, an object is to be created after a costly database operation.
3. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

What Is Prototype Pattern?

1. Prototype pattern refers to creating duplicate object while keeping performance in mind.
2. This pattern involves implementing a prototype interface which tells to create a clone of the current object.

Name Some Of The Design Patterns Which Are Used In Jdk Library?

ollowing are some of the design patterns which are used in JDK library:

1. Decorator patttern is used by Wrapper classes.
2. Singleton pattern is used by Runtime, Calendar classes.
3. Factory pattern is used by Wrapper class like Integer.valueOf.
4. Observer pattern is used by event handling frameworks like swing, awt.

What Are The Difference Between A Static Class And A Singleton Class?

Following are the differences between a static class and a singleton class:

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

How Can You Create Singleton Class In Java?

It is two step process:

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

Give some examples of Behavioral Patterns and how they are used.

Some of the most common Behavioral Patterns are:

a) Iterator -This design pattern is used to access elements of a collection sequentially hiding the internal implementation.

b) Chain of Responsibilities – This design pattern is used where a chain of objects is used to handle the responsibilities. In this design pattern, a request to process the client call is only passed to the next object when the first object fails to process the same.

c) Observer – It is used where a one-to-many relationship exists among the objects and modifying a single object can impact the dependent objects.

d) Mediator -This design pattern encapsulates the communication complexity takes place between different objects and acts as an intermediary between the objects for communication.

How are new Observers added to existing ones?

This is achieved after applying the Observer Pattern and adding them dynamically without requiring any changes to the Subject Class. Also, Observers remain unaffected when the state chance logic of the subject changes.

What problem does the Business Delegate Pattern try to solve?

When the presentation tier or client application accesses the business tier directly, the business service API is exposed to the client application or presentation tier. So if the business API changes, the corresponding changes will have to be made in the presentation tier. Also, in such an implementation, there is a performance issue as well, since the business service is invoked each time by the client application. Thirdly, this kind of implementation causes a tight coupling between the presentation tier and the business tier. The business delegate pattern solves all these problems. The Business Delegate class is present on the client side and it hides the implementation details of the business tier by providing an abstraction. So the client application only interacts with the delegate class which in turn routes the client’s request to the appropriate business method.

What happens with the response to the request in the case of these two patterns?

In the case of Proxy Pattern, the response to the request is guaranteed, provided the communication between the client and the server locations is working.

In the case of Chain of Responsibility, the response is not guaranteed. It means that the request may end up reaching the end of the chain and still might not be processed.

What is the main advantage of the Facade Pattern?

The Facade Pattern helps in hiding the complexities of the application beneath the layer of an interface. This interface helps in reducing the dependency of the client classes on the subsystem classes, thus resulting in a manageable and user-friendly subsystem.

Name Types Of Design Patterns?

Design patterns can be classified in three categories:

<> Creational patterns
<> Structural patterns
<> Behavioral patterns

What Is Gang Of Four Gof?


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

What about anti-patterns?

Of course, using the wrong design pattern can have a very negative effect on your code. So, it takes good judgement to use the correct design pattern. The term “anti-pattern” is used to describe a poor programming practice that leads to ineffective code.

Why should we use design patterns?

Design patterns are useful because they provide a pre-formulated solution to problems based on the experience of other programmers. This can save you a lot of time.

Design patterns also help in communication of a programming solution, and provide a common technical vocabulary between programmers.

Design patterns versus frameworks

Are design patterns the same thing as frameworks? The answer to that is no. Design patterns are more like general guidelines on how to solve specific programming problems, but they do not specify the detailed code that’s necessary to solve those problems.

Where did design patterns originate from?

Although design patterns were probably used by programmers for many years before, design patterns were formally introduced in computer science in a book called “Design Patterns: Elements of Reusable Object-Oriented Software”. This book was published in 1994 and is still considered to be the bible of design patterns. There are four people who wrote the book, and they are commonly referred to as the Gang of Four, or GoF (even Go4) for short – many times GoF is even used to refer to the book itself.

How would you create your own Instagram?

Instagram is a photo-sharing application that provides some custom filters to enhance your photo quality. Your application should have photo upload functionality, tagging photos for search, and some basic filters. If you could add share or social network that could be great.

How do you design a website like Pastebin?

Pastebin allows you to paste text or code and then share a link to that code anywhere you want. It’s not an online code editor but you can use this to store any kind of text.

How to design a limit order book for trading systems?

A limit order book is used in stock exchanges to match a buy order with a sell order based on price and time priority. How would you go about that? Which data structure you will use? Remember, the speed of matching is key and also the reliability.

How do you design a traffic control system?

A classical system design question from old age which is still popular. Make sure you know how to transition from one state to another like RED to GREEN and from GREEN to ORANGE to RED etc.

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

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 is internally called the paint() method of individual components and let them draw themselves.

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.

What is Prototype Design Pattern and when to use it?

It is a creational design pattern which is used in cases when a large number of instances of a class are required and these instances are almost identical but may have slightly different properties. This pattern is useful in cases wherever there is high time and cost overhead associated with the object creation. This pattern mainly works by creating clone of the existing object instead of creating a new instance every time so that performance is optimized.

Which design pattern is preferred for creating a complex object?

Builder design pattern is more suitable for creating complex object as it is an extension of Factory pattern and is created for solving the issues associated with Factory and Abstract Factory design patterns.

Difference between Proxy and Adapter?

Adapter object has a different input than the real subject whereas Proxy object has the same input as the real subject.

Proxy object is such that it should be placed as it is in place of the real subject.

Search
R4R Team
R4R provides Design Patterns Freshers questions and answers (Design Patterns Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,Design patterns interview questions part 2,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, ASP.net 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 r4r.in .learn in easy ways .