Tech Point Fundamentals

Friday, May 6, 2022

Design Patterns Interview Questions - Part 10

Design Patterns Interview Questions and Answers - Part 10


In Software Industry the Design Patterns and Principles are always followed. So this is the most common topic for the interview. In this article, we will see the most frequently asked 90+ Design Patterns and Principles Interview Questions with Answers

Please visit our YouTube Channel for Interviews and other videos by below link:

Please read the complete C# Interview Questions and Answers article series here.


This is the 10th part of this Design Patterns and Principles Interview Questions and Answers article series. Each part contains five Design Pattern Interview Questions. Please read all the Design Patterns and Principles Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:

Design Patterns Interview Questions - Part 10

Q74. What are the Behavioral Design Patterns (BDP)? What are the different Behavioral Design Patterns?

Behavioral patterns are about identifying common communication patterns between objects and realizing these patterns. Behavioral design patterns are concerned with the interaction and responsibility of objects.

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

In these design patterns, the interaction between the objects should be in such a way that they can easily talk to each other and still should be loosely coupled.  the implementation and the client should be loosely coupled in order to avoid hard coding and dependencies.

There are 12 types of behavioral design patterns:

  1. Chain of Responsibility Pattern: This pattern delegates commands to a chain of processing objects.
  2. Command Pattern:  It creates objects which encapsulate actions and parameters.
  3. Interpreter Pattern: This pattern implements a specialized language.
  4. Iterator Pattern: This pattern accesses the elements of an object sequentially without exposing its underlying representation.
  5. Mediator Pattern: This pattern allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
  6. Memento Pattern: This pattern provides the ability to restore an object to its previous state.
  7. Observer Pattern: This is a publish/subscribe pattern which allows a number of observer objects to see an event.
  8. State Pattern: This allows an object to alter its behavior when its internal state changes.
  9. Strategy Pattern: This allows one of a family of algorithms to be selected on the fly at run-time.
  10. Template Method Pattern: This pattern defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
  11. Visitor Pattern: This separates an algorithm from an object structure by moving the hierarchy of methods into one object.
  12. Null Object Pattern: This pattern uses a null object which can be bound at runtime.

Q75. What is Iterator Design Pattern (IDP)? When to use the Iterator Behavioral Design Pattern?

An iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.). This pattern is used to get a way to access the elements of a collection object in a sequential manner without any need to know its underlying representation.

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

No matter how a collection is structured, it must provide some way of accessing its elements so that other codes can use these elements. The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a separate object called an iterator. It provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

The iterator pattern iterator object encapsulates all of the traversal details, such as the current position and how many elements are left till the end. Because of this, several iterators can go through the same collection at the same time, independently of each other. In .Net the IEnumerator implements the Iterator pattern.

Use the Iterator pattern when your collection has a complex data structure under the hood, but you want to hide its complexity from clients. This pattern is used to reduce duplication of the traversal code across your app. Use the Iterator when you want your code to be able to traverse different data structures or when types of these structures are unknown beforehand.

Q76. What is Observer Design Pattern (ODP) or Event-Subscriber Pattern?  When to use the Observer Behavioral Design Pattern?

An observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing. It defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

The observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used for implementing distributed event handling systems, in "event-driven" software. 

The object that has some interesting state is often called a subject, but since it’s also going to notify other objects about the changes to its state, we’ll call it a publisher. All other objects that want to track changes to the publisher’s state are called subscribers.

The Observer pattern suggests that you add a subscription mechanism to the publisher class so individual objects can subscribe to or unsubscribe from a stream of events coming from that publisher. 

Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing "observer" and "subject" objects, whereas a Mediator object encapsulates the communication between other objects.

Q77. What is Mediator Design Pattern (MDP) or Controller Pattern?  When to use the Mediator Behavioral Design Pattern?

It is also known as Intermediary Pattern or Controller Pattern. A mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object.

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other, but instead, communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling.

It defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

The Mediator pattern suggests that you should cease all direct communication between the components which you want to make independent of each other. Instead, these components must collaborate indirectly, by calling a special mediator object that redirects the calls to appropriate components. As a result, the components depend only on a single mediator class instead of being coupled to dozens of their colleagues.

Use the Mediator pattern when it’s hard to change some of the classes because they are tightly coupled to a bunch of other classes. You can reduce coupling between various components of a program because the tight coupling between a set of interacting objects should be avoided. It should be possible to change the interaction between a set of objects independently.

Q78. What is Interpreter Design Pattern (IDP)?

In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client.

The Interpreter pattern defines a domain language (problem characterization) as a simple language grammar, representing domain rules as language sentences, and interpreting these sentences to solve the problem. The pattern uses a class to represent each grammar rule. And since grammars are usually hierarchical in structure, an inheritance hierarchy of rule classes maps nicely.

An abstract base class specifies the method interpret(). Each concrete subclass implements interpret() by accepting (as an argument) the current state of the language stream and adding its contribution to the problem-solving process.

Interpreter pattern provides a way to evaluate language grammar or expression. This pattern involves implementing an expression interface that tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engines, etc.

Component of Interpreter Pattern:

AbstractExpression: It declares an interface for executing an operation.

TerminalExpression: It implements an Interpret operation associated with terminal symbols in the grammar.

NonterminalExpression: It implements an Interpret operation for nonterminal symbols in the grammar.

Context: It contains information that is global to the interpreter.

Client: It invokes the Interpret operation.

Q79. What is Command Design Pattern (CDP) or Action Pattern?

This pattern is also known as the Action Pattern or Transaction Pattern. The command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.

The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method, and values for the method parameters.

Using command objects makes it easier to construct general components that need to delegate, sequence, or execute method calls at a time of their choosing without the need to know the class of the method or the method parameters. 

Components of Command Pattern:

There are four terms that are associated with the command pattern i.e command, receiver, invoker, and client. 

Command: A command object knows about the receiver and invokes a method of the receiver. 

Receiver: Values for parameters of the receiver method are stored in the command. The receiver object to execute these methods is also stored in the command object by aggregation. The receiver then does the work when the execute() method in command is called. 

Invoker: An invoker object knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker does not know anything about a concrete command, it knows only about the command interface.

Client: Invoker object(s), command objects, and receiver objects are held by a client object, the client decides which receiver objects it assigns to the command objects, and which commands it assigns to the invoker. The client decides which commands to execute at which points. To execute a command, it passes the command object to the invoker object.

Q80. What is Memento Design Pattern (MDP) or Snapshot Pattern?

It is also known as Snapshot Pattern. Memento is a behavioral design pattern that lets you save and restore the previous state of an object without revealing the details of its implementation.  Memento Design Pattern without violating encapsulation, capture and externalize an object's internal state so that the object can be returned to this state later.

The client requests a Memento from the source object when it needs to checkpoint the source object's state. The source object initializes the Memento with a characterization of its state. The client is the "caretaker" of the Memento, but only the source object can store and retrieve information from the Memento. If the client subsequently needs to "roll back" the source object's state, it hands the Memento back to the source object for reinstatement.

The Memento pattern delegates creating the state snapshots to the actual owner of that state, the originator object. The pattern suggests storing the copy of the object’s state in a special object called a memento. The contents of the memento aren’t accessible to any other object except the one that produced it. Other objects must communicate with mementos using a limited interface which may allow fetching the snapshot’s metadata (creation time, the name of the performed operation, etc.), but not the original object’s state contained in the snapshot.

Components of Memento Pattern:

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback). The memento pattern is implemented with three objects: the originator, a caretaker, and a memento.

Originator: The originator is some object that has an internal state.  It is an object that knows how to save itself.

Caretaker: This is the object that knows why and when the Originator needs to save and restore itself. The caretaker is going to do something to the originator but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. 

Memento: It stores the internal state of the Originator object. It protects against access by objects other than the originator.  

Q81. What is State Design Pattern (SDP)?

The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.

The state pattern is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class.

The main idea is that, at any given moment, there’s a finite number of states in which a program can be. Within any unique state, the program behaves differently, and the program can be switched from one state to another instantaneously. However, depending on the current state, the program may or may not switch to certain other states. These switching rules, called transitions, are also finite and predetermined.

The State pattern suggests that you create new classes for all possible states of an object and extract all state-specific behaviors into these classes. Instead of implementing all behaviors on its own, the original object called context, stores a reference to one of the state objects that represents its current state, and delegates all the state-related work to that object.

To transition the context into another state, replace the active state object with another object that represents that new state. This is possible only if all state classes follow the same interface and the context itself works with these objects through that interface.

To Be Continued Part-11...

Recommended Articles

Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK, for regular updates.


External Reference:

  1. Wikipedia
  2. RefacturingGuru
  3. SourceMaking

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.