DESIGN
PATTERNS
LAST MINUTE INTERVIEW GUIDE
SANDEEP BONAGIRI
What’s a Design Pattern? Creational Patterns
Design patterns are recognized approaches to
solve commonly occurring problems in software Singleton
design. They are like pre-made blue-prints that
you can customize to solve a recurring Singleton is a creational design pattern that
object-oriented design problem in your code. lets you ensure that a class has only one
instance, while providing a global access
point to this instance.
Categories of Design
Analogy
Patterns
The LoggerService class, using the Singleton pattern,
ensures efficient memory use in a project by creating
Creational Patterns a single, globally accessible instance for logging
information, warnings, and errors, thus preventing
Creational design patterns simplify object out-of-memory errors.
creation in software design, allowing for
flexibility and code reuse. By providing
mechanisms to handle varying object
nature, these patterns reduce complexity
and enhance the overall design.
Structural Patterns
Structural design patterns organize objects
and classes to achieve multiple objectives. Structure
They illustrate how system components can
be combined in a flexible and extensible
manner, facilitating targeted modifications
without impacting the entire structure.
Behavioral Patterns
Behavioral design patterns address object
interaction in software applications and
offer solutions for common interaction
issues in object-oriented design. They
identify communication patterns among
objects and provide guidelines to solve
frequently encountered problems.
01 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Abstract Factory
Phone Tablet Laptop
The Abstract Factory pattern is an extension of the Factory
Android
pattern. It allows the creation of object families without
specifying concrete classes, resembling a hierarchical
factory of factories.
Analogy iOS
To ensure customer satisfaction, we create individual
products that match others within the family of Phone,
Tablet, and Laptop. Variants such as Android, iOS, and
Windows are available for these devices. Inconsistent Windows
combinations of food disappoint customers.
Structure
4
ConcreteFactory1
...
+createProductA(): ProductA
+createProductB(): ProductB
Concrete Concrete
ProductA1 2 ProductB1
3 5
<interface> Client
AbstractFactory -factory: AbstractFactory
ProductA 1 ProductB
+createProductA(): ProductA +Client(f: AbstractFactory)
+createProductB(): ProductB +someOperation()
Concrete Concrete
ProductA2 2 ProductB2
4
ConcreteFactory2
...
+createProductA(): ProductA
+createProductB(): ProductB
02 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Builder Prototype
The Builder pattern constructs complex The Prototype pattern creates new objects
objects incrementally, similar to building a by copying existing ones, ensuring code
multi-layered cake. Each step adds an independence from their classes. It enables
ingredient or component, allowing the creation of prototype objects that
customization and diversity using a replicate the original ones.
consistent building process.
Analogy
Analogy
Say, you want to create an exact copy of an
Customer details are stored in a database object. To perform this, you need to know
using a Customer class with mandatory the class of the object and its fields which
fields (First Name, Last Name, Primary may be private. Prototype delegates the
Email, and Primary Mobile Number) and work of cloning objects to the actual object
optional fields (Middle Name, Secondary itself.
Email, and Secondary Mobile Number)
passed as null values using the builder One Month After
design pattern for flexible object creation. “ Do you think wedʼ be
able to copy it? ” “Perfect!”
Structure
Structure
03 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Factory Method
The Factory pattern is a creational design
pattern that separates object creation logic
from client code. A factory class uses a
method to create objects based on client
requests.
Analogy
Consider a milkshake bar. Customers order
from a waiter, the order goes to the kitchen,
and the kitchen prepares the milkshakes.
The kitchen is like a shake factory, taking
and fulfilling orders.
Structure
Sandeep Bonagiri
04 Design Patterns
@bonagirisandeep
Structural Patterns
Adapter
The Adapter pattern acts as a bridge between
initially incompatible interfaces, facilitating
collaboration between objects.
Analogy
A weather forecasting application retrieves Application
JSON-formatted weather data from multiple Core Classes
sources and displays visually appealing JSON JSON x CSV
forecasts and maps. To improve functionality,
Weather Data Machine Learning
integrating a machine learning library that Provider Library
only supports CSV data format becomes a
challenge.
Structure
Interface
Image Viewer
Interface
Advanced Image Viewer
+Show(): Void
+ShowPng(): void
+Showjpg(): void implements implements
implements implements
Image Adapter Gallery App
-advancedImage -imageAdapter:
Png Shower Jpg Shower Viewer: ImageAdapter
uses uses
AdvanceImage
Viewer
+ShowPng() +ShowPng()
+ImageAdapter()
+ShowJpg() +ShowJpg()
+Show() +Show(): Void
Sandeep Bonagiri
05 @bonagirisandeep Design Patterns
Bridge
The Bridge pattern separates complex classes
into abstraction and implementation hierarchies,
allowing flexible connectivity through object
composition for easier development and
maintenance.
Analogy
In designing a multimedia application,
different views like Long and Short views
are implemented to present media content
such as artist information and music albums.
Structure
06 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Composite
Structure
The Composite pattern creates tree-like 4
structures by combining objects, allowing Client
uniform manipulation of object collections
regardless of hierarchy. It enhances code
extensibility and modularity when working 1
with complex object arrangements. <<interface>>
Component
+execute()
Analogy
Consider a scenario where you have two
types of objects: Files and Folders. A Folder 2 3
can contain multiple Files as well as smaller Leaf Composite
Folders. These smaller Folders can also hold ... -children: Component
Files or even smaller Folders, forming a +execute() +add(c: Component)
hierarchical structure. +remove(c: Component)
+getChildren(): Component[]
+execute()
Complex Folder
Decorator
The Decorator design pattern enables the
addition of new functionalities to objects by
wrapping them in special wrapper objects.
File A
This approach allows for dynamic behavior
extension without impacting the behavior
of other objects in the same class.
File B
Analogy
In the decorator design pattern, a pizza
File C File D File E servesas the original class while various
toppings represent added functionalities.
Customers can customize their pizza by
adding toppings without altering the base
structure.
07 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Facade
Structure
The Facade pattern provides a simple
interface to interact with a complex system,
shielding clients from underlying complexities
and dependencies. It acts as a bridge, offering
easy access to desired functionalities without
revealing internal workings.
Analogy
In the Facade design pattern, when placing
an order over the phone, the operator acts as
a simplified interface to access various
services offered by the shop. The facade layer
assigns tasks to the appropriate subsystem
based on user input.
Structure
08 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Flyweight Facade
The Flyweight design pattern optimizes The Proxy pattern acts as a substitute for a
memory usage by sharing common state real object, serving as an intermediary
among multiple objects instead of between the client and the actual object.
duplicating it, allowing for efficient It provides control over actual object-access,
utilization of available resources when allows for additional functionality, and
creating numerous objects. enables client access restrictions.
Analogy Analogy
In the open-world game, the Flyweight For an Instagram-like app on limited-resource
designpattern minimizes memory usage by smartphones, we design an Image interface
storing shared states (color and height) with operations like border determination,
within the Flyweight object and unshared rendering, and screen display. This interface
states (position) externally. This optimization ensures efficient image loading and display
eliminates redundant storage of duplicate functionality in the application.
values for efficient memory utilization.
Application for Resource-Bound Device
Game
Brown tree
Green tree
Green tree
Green tree
Brown tree
Green tree
Green tree Brown tree
Structure
Structure
Proxy Design Pattern
09 Design Patterns
Sandeep Bonagiri
@bonagirisandeep
Behavioral Patterns
Chain of Responsibility Command
Chain of Responsibility is a behavioral design The Command pattern transforms requests
pattern that lets you pass requests along a or operations into self-contained objects,
chain of handlers. Upon receiving a request, encapsulating information such as the
each handler decides either to process the method and its arguments. This abstraction
request or to pass it to the next handler in enables method parameterization, queued
the chain. request execution, and support for undoable
operations.
Analogy
The ATM Machine exemplifies the Chain of Analogy
Responsibility pattern: it handles the The Command design pattern is illustrated
responsibility chain, from card insertion to by a universal remote with configurable On,
cash withdrawal, delegating tasks to Off, Up, and Down buttons. These buttons
appropriate handlers. Requests are can be assigned actions based on the device,
processed systematically, achieving the like adjusting brightness or volume,
desired result. implemented through command objects.
Speaker Remote Light
Structure Structure
10 Sandeep Bonagiri
Design Patterns
@bonagirisandeep
Iterator
Iterator is a behavioral design pattern that
lets you traverse elements of a collection
without exposing its underlying Collections(List,ArrayList,Array,etc)
representation (list, stack, tree, etc.).
Analogy
In an application that tracks a collection of
alerts, the Iterator design pattern enables
iteration through the alerts without exposing
the underlying structure. This pattern ensures
seamless and controlled traversal of the
collection.
Structure
11 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Mediator
The Mediator pattern reduces dependencies
and promotes organized communication
between objects. It introduces a mediator
object to restrict direct communication and
enforce interactions through the mediator.
Analogy
In a restaurant kitchen, chefs rely on an
expediter who acts as a central communicator.
The expediter relays orders, ensuring smooth
coordination. Without this, chefs face potential
confusion and delays.
Structure
12 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Memento
Input Memento Application
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.
Analogy Store/save Rollback/Restore
The Memento pattern delegates state snapshot
creation to the originator object. Snapshots are
stored in mementos, accessible only to the Undo operation
called
originator. Other objects have limited access, History/
obtaining metadata but not the original state. Checkpoints
Structure
Originator Memento Caretaker
-state -state -originator
-history: Memento[]
+save(): Memento -Memento(state)
+restore(m: Memento) -getState() +doSomething()
+undo()
13 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Observer State
Observer is a behavioral design pattern that
lets you define a subscription mechanism to The State pattern allows an object to change
notify multiple objects about any events that its behavior based on internal state changes,
happen to the object theyʼre observing. resembling finite state machines. It avoids
excessive conditional statements and provides
flexibility in altering an object's state.
Analogy
Analogy
Subscribing to a newspaper or magazine
ensures direct delivery to your mailbox, In a video game, the behavior of buttons and
eliminating the need to check availability at controls changes depending on the game
a store. Publishers send new issues promptly state. Such as during gameplay, pressing
or in advance for convenience. buttons triggers various in-game actions,
when the game is paused, pressing any
button brings up the pause menu and so on.
The New York Times
Structure
Structure
1 2
Context <<interface>>
-state State
-Context(initialState) +doThis()
+changeState(state) +doThat()
+doThis()
+doThat()
3
ConcreteStates
-context
+setContext(context)
Client +doThis()
+doThat()
14 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Strategy Template Method
Strategy is a behavioral design pattern that The Template Method pattern defines the
lets you define a family of algorithms, put structure of an algorithm in a superclass,
each of them into a separate class, and make allowing subclasses to override specific steps
their objects interchangeable. without changing the overall structure. It
provides a skeleton of functions, enabling
child classes to implement method details
Analogy while the parent class maintains the
When going to the airport, transportation algorithm's framework and sequencing.
strategies such as bus, cab, or bicycle offer
options based on factors like budget and
time constraints, enabling you to choose Analogy
the most suitable approach. Frameworks extensively utilize the Template
Method Design Pattern, executing immutable
domain components and providing
placeholders for user modifications. The
framework becomes central, while client
modifications are secondary.
x x x x x
Structure x x x x x
1 2
Context <<interface>>
Structure
-strategy Strategy
+execute(data)
+setStrategy(strategy)
+doSomething(
3
4 ConcreteStrategies
Client
+execute(data)
15 Sandeep Bonagiri Design Patterns
@bonagirisandeep
Visitor
The Visitor pattern separates algorithms from the
objects they operate on. It uses visitor classes to
handle specific operations on objects. This
decoupling enhances flexibility and extensibility,
enabling different operations on objects without
modifying their structure.
Area Calculator Perimeter Calculator
Analogy
The Visitor design pattern decouples algorithms
from shape objects, allowing easy addition of
new algorithms without modifying the objects.
This promotes extensibility and adheres to the Output Output
Open/Closed principle.
Structure
16 Sandeep Bonagiri Design Patterns
@bonagirisandeep
VI. Design Pattern Principles
- SOLID principles: Guide for object-oriented design and programming.
- DRY (Don't Repeat Yourself) principle: Avoid repetition of code.
- KISS (Keep It Simple, Stupid) principle: Simplicity should be a key goal.
- YAGNI (You Aren't Gonna Need It) principle: Don't add functionality until needed.
VII. Choosing the Right Design Pattern
- Understand the problem context thoroughly.
- Match problem characteristics with design patterns.
- Analyze the trade-offs and benefits of each pattern.
- Check pattern compatibility with the existing system.
VIII. Design Pattern Best Practices
- Don't overuse design patterns - keep it simple.
- Adapt patterns to fit your needs; they are not strict rules.
- Aim for simplicity and maintainability in your code.
- Continuously refactor and improve your code.
Start Learning
17 Sandeep Bonagiri Design Patterns
@bonagirisandeep