DP Full Answers
DP Full Answers
hen designing software (or anything for that matter), it is common to face the same
W
problems over and over again. Eventually, you build up enough knowledge of a problem to
define a general solution for solving that problem every time you meet it. A design pattern is
like a template for solving a specific (and well-defined) problem.
W hat is MVC?
VC is a design pattern that divides an application into three interconnected components to
M
s eparate concerns and improve modularity, maintainability, and scalability:
1. M odel: Represents the data, business logic, and state of the application. It’s the
"truth" of the system, independent of how it’s displayed or interacted with.
2. View: The user interface (UI) that displays the Model’s data to the user. It’s a visual
representation of the Model and doesn’t handle logic itself.
3. Controller: The intermediary that handles user input, facilitating communication
between the Model and View, ensuring they stay in sync without being tightly coupled.
he goal is to keep these components loosely coupled, so changes in one (e.g., updating the
T
UI) don’t require rewriting the others (e.g., the data logic).
his Question also rephrase as like this ⇒ b) Describe the design patterns using a consistent
T
format. 4. a) Explain the role of pattern elements in design of a particular problem.
● Why: Clarifies the problem it solves and its variations in naming.
3. Motivation
● What: Real-world scenario showing the need for this pattern.
4. Applicability
● Why: Helps you pick the right pattern at the right time.
5. Structure
6. Participants
7. Collaborations
8. Consequences
● What: Benefits and drawbacks of using the pattern.
9. Implementation
● What: Tips, pitfalls, and techniques for coding the pattern.
● Why: Helps translate the pattern into your own project.
Class Scope
● F
actory Method: Defines an interface for creating objects, but subclasses decide
which class to instantiate.
Object Scope
● A
bstract Factory: Creates families of related objects without specifying concrete
c lasses.
● B
uilder: Separates object construction from its representation (step-by-step
c onstruction).
● Singleton: Ensures a class has only one instance and provides global access to it.
🧱 Structural Patterns
Focus: How classes/objects are composed.
Class Scope
● Composite: Composes objects into tree structures (e.g., menus, UI elements).
🤖 Behavioral Patterns
Focus: Communication between objects.
Class Scope
● T
emplate Method: Defines a skeleton of an algorithm, allowing subclasses to
override specific steps.
Object Scope
Identify the right set ofobjectsand theirresponsibilities. It’s about breaking down the
problem domain into classes that reflect real-world entities and operations.
Decidehow many objectsyou need and how "fine-grained" each object should be.
● Too fine: Makes the system complex and hard to manage.
Design clearinterfacesfor objects, defining how they interact with other parts of the system.
💡
Patterns like Strategy, Observer, and Command depend heavily on well-defined
interfaces.
eterminehowan object fulfills its responsibilities. This involves selecting data structures,
D
algorithms, and internal logic.
💡 Encapsulation and hiding internal implementation details are key here.
💡 M any design patterns encourage interface-based design (e.g., Bridge, Strategy).
rite code that depends onabstractions(interfaces), not concrete classes. This makes
W
c odeflexibleande asier to change.
💡 Use
Shapeinstead of
Circleor
Rectangledirectly.
// BAD
Circle c = new Circle();
// GOOD
Shape s = new Circle();
O pen/Closed Principle: Open for extension, closed for modification. 💡 Patterns like
💡
Strategy, Observer, and State support changeable behavior.
l) Toolkits
💡
Design patterns help build generic, reusable components (e.g., using Template Method or
Abstract Factory in a GUI toolkit).
m) Frameworks
💡
Frameworks often use multiple design patterns to allow extension and reuse (e.g., React
uses Composition, Observer pattern, etc.).
istinguish between Object-Oriented
D
Software and Design Patterns:
Example Student
A student management system with Teacher
, Coursec lasses.
,
🔹 Design Patterns:
Aspect Description
Definition A
reusable solutionto a common design problem that occurs within a
particular context in software design. Design patterns areblueprintsor best
practices, not actual code.
Deals with how software is built Deals with how software is designed
🔹 Key Points:
1. Encapsulation
○ Implementation details are kept private to protect data integrity and prevent
m isuse.
4. M odifiability
○ C
hanges to the internal implementation do not affect other parts of the system
as long as the interface remains the same.
Example in Java:
c lass Car {
private int speed; // attribute (hidden)
5.
setSpeed()and
○ The user interacts with getSpeed()but does not know
speedis internally stored or validated.
how
🔹 In Design Patterns:
● P
atterns likeStrategy,Decorator, orBridgehelp separate the interface from the
implementation.
exi is a document editor, and like any modern editor, it needs aflexible and efficient user
L
interfaceto handle different elements like text, images, graphics, and windows. The
c hallenge in designing Lexi’s UI comes fromthe need to support multiple windowing
systems, ensure flexibility, and maintain an efficient layout.
2. Formatting
● T ext formatting (font styles, colors, alignment) must be applied efficiently to different
parts of the document.
● It should allow global styles and individual customizations without affecting
performance.
● Solution:
○ Decorator Patternenables applying formatting styles dynamically without
m odifying the core document structure.
How It Works
How it works:
xample:
E
If you type “recieve”, the spell checker will highlight it and suggest “receive”.
ii) Hyphenation
efinition:
D
Hyphenation is the process ofbreaking words between lines using hyphens (-)to
improve text layout and alignment, especially in justified text.
Purpose:
xample:
E
Instead of moving the whole word “dictionary” to the next line, it can be split as:
dic-(end of one line)
tionary(beginning of next line)
collaborative document editor like Google Docs serves as a case study. It involves real-time
A
editing, collaboration, and versioning, ideal for design patterns.
Application of Design Patterns
● M VC (Architectural):
○ M odel: Manages document content and syncs with a server.
○ View: Displays the UI, updating in real-time.
○ Controller: Handles inputs and coordinates Model/View.
○ Support: Separates concerns for modularity.
● O bserver (Behavioral):
○ Application: Notifies all clients of changes for real-time collaboration.
○ Support: Ensures consistency across users.
● Command (Behavioral):
○ Application: Encapsulates actions for undo/redo.
○ Support: Enables versioning and user recovery.
● Strategy (Behavioral):
○ Application: Swaps formatting algorithms (e.g., bold, italic).
○ Support: Adds flexibility.
● Decorator (Structural):
○ Application: Dynamically adds text features (e.g., bold).
○ Support: Keeps structure extensible.
● Singleton (Creational):
○ Application: Ensures one document manager instance.
○ Support: Centralizes control.
Support Methods
● se frameworks (e.g., React, Node.js) for MVC.
U
● Implement WebSocket for Observer-based sync.
● Design extensible APIs for Strategy/Decorator.
● Test pattern components (e.g., Command).
● Use cloud storage for scalability.
● Document pattern usage for consistency.
● O verview: A document editor (e.g., Microsoft Word, Google Docs) allows text
c reation, editing, and formatting.
● Key Components:
1. View: Intuitive UI for input/output.
2. M odel: Stores content and supports operations.
3. Controller: Manages inputs and updates.
4. Storage: Saves to files or cloud.
● Design Considerations:
1. Use Observer for real-time collaboration.
2. Apply Command for undo/redo.
3. Use Strategy/Decorator for formatting.
. Use Singleton for session control.
4
5. Adopt MVC for modularity.
● Implementation:
1. Define Model (e.g., text array).
2. Create View (e.g., HTML).
3. Develop Controller (e.g., event listeners).
4. Integrate patterns.
5. Test performance/usability.
Challenges: Managing concurrent edits, optimizing large documents, ensuring
●
c ompatibility.
● Conclusion: Patterns make the editor robust and collaborative.
✅ Meaning:
If two or more modules have someoverlapping functionality, that shared part is the
intersection.
💡 Example:
●
Printer
●
Scanner
📊 In Set Theory:
✅ Meaning:
💡 Example:
●
Printerhas: {print, connect}
●
Scannerhas: {scan, connect}
Then:
xample in
E trategy pattern focuses on thecommon interface(intersection), while
S
Design a framework might provide thefull range(union)
UNIT_3
Abstract Factory Pattern ?
Applicability:
Use the Abstract Factory Pattern when:
● A
system should beindependent of how its products are created, composed,
and represented.
● You want toe nforce consistency among productsfrom the same family.
● You want to hide the product implementations and expose only interfaces.
Consequences (Benefits):
● Isolationof concrete classes.
Related Patterns:- •
he Builder Pattern has several consequences, both positive and negative, which make it suitable for
T
specific use cases:
Positive Consequences:
1. S
eparation of Concerns:
The construction process is separated from the representation of the object. This makes the
code more modular and easier to maintain.
1. F
ine-Grained Control:
The pattern allows step-by-step construction of complex objects, giving developers precise
control over the creation process.
1. R
eusability:
The same construction process can be reused to create different representations of the
object.
1. I mproved Readability:
The construction logic is encapsulated in a separate builder class, making the code more
readable and easier to understand.
1. F
lexibility:
New types of products can be introduced without modifying the existing construction code.
This makes the system more extensible.
1. A
voids Telescoping Constructors:
The Builder Pattern eliminates the need for constructors with many parameters (telescoping
constructors), which can be hard to maintain and understand.
Negative Consequences:
otivation:
M
The Adapter pattern lets youintegrate incompatible interfaceswithout modifying their
s ource code. It provides abridge between old and new systems, promotingreusability
andflexibilityin your software design.
2. a) Uses and Related Patterns of Bridge Design Pattern
3. H
elps avoid class explosion(when every combination of abstraction and
implementation leads to a new subclass).
🔗 Related Patterns:
● A
dapter: Makes two incompatible interfaces work together but doesn’t separate
abstraction from implementation.
● Abstract Factory: Can be used to create different implementations for the bridge.
● S
trategy: Also separates concerns, but Bridge focuses on abstraction vs
implementation while Strategy focuses on behaviors.
Definition:
Refined Abstraction xtends the Abstraction andcustomizesit (e.g., a specific type of
E
abstraction).
oncrete
C Implements the Implementor interface withspecific behavior.
Implementor
Composite Design Pattern
Known Uses:
Decorator lso involves recursive structures, but adds behavior rather than
A
c omposition.
● Componentdefines the interface for objects that can have added responsibilities.
● D
ecoratorm aintains a reference to a Component object and implements the
Component interface.
● C
oncreteDecoratoradds new behavior before/after delegating work to the
Component object it wraps.
📌
The decorator wraps the component and forwards requests to it, potentially adding
behaviorbefore or afterthe forwarding.
🌍 Known Uses:
Java I/O Streams
.
1
2. G UI Libraries
🔗 Related Patterns:
Pattern Relation to Decorator
Proxy ontrols access, may look similar to a decorator, but the intent
C
differs (access control vs. behavior extension).
hain of
C imilar in structure; passes requests through a chain, but focuses
S
Responsibility on who handles it, not adding behavior.
○ It hides the complexities of the subsystem and provides a cleaner,
easier-to-use interface.
○ C
lients interact with the facade instead of multiple subsystem classes directly.
This promotesloose coupling.
○ W
ith a simplified interface, the overall readability of code increases, especially
when many operations are bundled.
○ C
lients can still use subsystem classes if needed. The pattern doesn’t restrict
direct access.
○ C
hanges in the subsystem might not affect the clients, reducing the need for
recompilation.
○ O
r usecomposition: Inject or configure subsystem objects inside the Facade
to allow flexibility.
○ F
acade class can be customized or extended by replacing some of the
s ubsystem objects.
○ S
ubsystems may expose some classes publicly (used by clients) and keep
others private (used internally).
○ F
açade is a part of thepublic API; private subsystem classes are used only
within the module or library.
○ Decide which methods and operations the facade should expose.
○ D
on’t overload the facade with too much logic—it should delegate to the
s ubsystem, not replace it.
🚀 Motivation for Flyweight Pattern
● W hat varies is thepositionof the character, maybe itsstyle(bold, italic) orcolor.
● Create asingle shared object per character(like a shared 'a', 'b', etc.)
● W hen the image is needed (like on display), the proxy loads itlazily.
○ D
efines thecommon interfaceforRealSubjectandProxys o that a proxy
c an be used wherever a real object is expected.
2. RealSubject
○ C
lients ultimately want to interact with this, but it may be expensive or
restricted.
○ Responsible for tasks like lazy loading, logging, security, or remote access.
4. Client
○ U
ses theSubjectinterface to interact with the real object through the proxy,
without knowing whether it's talking to a proxy or the actual object.
1. Remote Proxy: Hides the object's location (e.g., remote server).
2. Virtual Proxy: Delays object creation until needed, saving resources.
3. P
rotection Proxy / Smart References: Adds security or housekeeping before
access.
○ U
sesreference countingand only copies when needed, saving memory and
time.
○ P
roxies can work through abstract interfaces to avoid knowing the exact type
of the real subject.
Chain of Responsibility:
✅ Intent
o avoid coupling the sender of a request to its receiver by giving more than one object a
T
c hance to handle the request.
The request is passed along a chain of handlers until one of them handles it.
💡 Motivation
Imagine a system where different objects handle different types of requests — like logging,
authentication, or validation. Rather than the sender knowing exactly who should handle the
request:
● The request is passed along the chain until a suitable handler is found.
xample:
E
A help desk system where user queries pass through different levels — L1, L2, and L3
s upport — until someone solves the issue.
🧩 Command Design Pattern [Action/Transaction]
✅ Intent:
🚀 Motivation:
ach button sends acommand, but the remote doesn’tneed to knowhowthose devices
E
work internally.
➡️
It just sends the right command to the right device.
📌 Use Cases:
🔁 Related Patterns:
Implementation Issues
Handlerc lass).
○ Can be done by adding explicit links (usually in the
✅ Applicability
execute()and
○ Commands can implement unexecute()(or
undo()
).
○ Easy to add new transactions with the common command interface.
🤝 Collaborations
● C
lient
ConcreteCommandand sets its receiver.
→ Creates
● Invoker
execute()
→ Stores and invokes the command using .
● C
oncreteCommand
→ Stores state (for undo), and calls receiver's operations to fulfill the request.
ollections like lists, trees, or hash tables have different internal structures. TheIterator
C
pattern allowsuniform accessto elements in thesec ollections without needing to know their
s tructure.
For example:
java
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
namesis an
You don’t need to know whether ArrayList LinkedList
, , etc.
Applicability
● You want toaccess elementsof a collection withoutexposing its internal structure.
🔧 Implementation Issues
3. Robustness
First
○ Common methods: Next
, IsDone
, CurrentItem
, .
○ R
equire dynamic allocation (via factory methods), which has a performance
c ost.
○ E
xternal iterators in recursive structures (like Composite pattern) must track
paths through nested elements.
○ A
"do-nothing" iterator useful for boundary conditions and simplifying traversal
logic.
Mediator Design Pattern
Intent:
● T
oreduce couplingbetween components (objects) byhaving them communicate
indirectlythrough amediator object.
● Promotesloose couplingby keeping objects from referringto each other explicitly.
Motivation:
● In complex systems, many objects interact with each other.
● M
ediator acts as acentral controller, managing communicationbetween
c omponents (colleagues).
● E
xample: In a UI, clicking a button updates a list and disables another button — all
m anaged via adialog mediator.
Applicability:
🧠 Memento Design Pattern
✅ Intent:
● C
apture and externalizean object’s internal state so it can be restored laterwithout
v iolating encapsulation.
ere’s a trimmed and well-structured version of theConsequencesandImplementationfor
H
theM emento Pattern:
🧠 Memento Pattern
✅ Consequences:
○ O
riginator doesn't need to manage history or rollback logic; Memento handles
it.
○ Saving full object state frequently can use lots of memory or resources.
○ M
anaging many mementos (especially over time) may increase memory
usage.
○ You need access control to separate wide and narrow interfaces.
○ Instead of storing the full state, Memento can storeonly the changes.
○ Useful for undoable operations like commands in a history list.
1. M
apping subjects to observers: Subjects store referencesto observers to notify
them when necessary.
2. O
bserving multiple subjects: Observers may dependon multiple subjects, allowing
them to track changes from different sources.
○ Notify
O ption 2: Clients are responsible for triggering .
4. Dangling references: To avoid this, subjects should notify observers upon deletion
s o they can reset their references.
5. Ensuring consistency: Subject state must be consistentbefore notifying observers.
○ Pull model: Subject sends minimal notification, andobservers request details.
7. S
pecifying modifications of interest: Observers canregister interest in specific
events, improving update efficiency.
8. E
ncapsulating complex update semantics: A ChangeManagerc an help manage
c omplex relationships and update strategies, reducing the need for subjects to track
observers directly.
Intent
M otivation
M otivation
In some scenarios, different classes share similar algorithms with slight variations. Instead of
duplicating the algorithm in each subclass, we can define the common steps in a base class
and let subclasses implement the variable parts. This ensures code reuse while giving
flexibility to modify specific steps of the algorithm.
○ If there are common steps in an algorithm that remain the same across
s ubclasses, they should be implemented once in the base class. Subclasses
c an then implement the varying parts of the algorithm.
○ W
hen there is common behavior shared across subclasses, the Template
Method pattern allows factoring and localizing this shared behavior in the base
c lass, reducing code duplication.
○ W
hen you encounter code with similar structures but different details in
s ubclasses, first identify the differences and then separate those into new
operations. Afterward, replace the differing parts with a template method that
c alls these new operations.
○ B
y defining a template method in the base class that calls specific "hook"
operations, the Template Method pattern allows subclass extensions only at
predefined points in the algorithm. This ensures the overall flow remains
c ontrolled while allowing customization at those points.
Implementation Issues of the Template Method Pattern
pure
○ Primitive operations that must be overridden by subclasses should be
virtual
.
○ T
he goal is to minimize the number of primitive operations that need to be
overridden by subclasses. The more operations that need overriding, the more
c omplex the pattern becomes.
○ O
perations that should be overridden can be prefixed to identify them, such as
DoCreateDocumentor
DoRead , following a consistentnaming strategy.
Known Uses
● T
emplate methodsare fundamental and often seen inm ost abstract classes where
algorithmic structure is defined.
Related Patterns
● F
actory Methods: Often called by template methodsto instantiate objects required
for the algorithm.
● S
trategy: Template methods use inheritance to varypart of an algorithm, while
s trategies delegate the entire algorithm to external objects.
Intent
heVisitorpattern lets you separate algorithms from the objects on which they operate. It
T
allows you to add new operations to existing object structures without modifying those
s tructures. The Visitor pattern is particularly useful when you need to perform operations on a
s et of objects with different types, and the operations vary depending on the type of the object.
M otivation
onsider a scenario where you have a collection of objects, and you want to apply different
C
operations to those objects. If you were to place all the operations inside the objects
themselves, the classes could become cluttered with unrelated behavior. Instead, you can
use the Visitor pattern to add new functionality to the object structure, making it easier to add
or modify operations without changing the object classes themselves.
○ If the object structure involves multiple classes with different interfaces and
you need to perform operations based on their concrete types, the Visitor
pattern is a good fit.
○ W
hen you have many distinct, unrelated operations that need to be performed
on objects, the Visitor pattern allows you to keep operations separate by
defining them in one class instead of cluttering the object classes.
○ If the object structure is shared across different applications, the Visitor pattern
lets you encapsulate operations in the applications that need them, avoiding
unnecessary coupling.
○ If the classes that define the object structure change infrequently but you need
to define new operations over the structure, the Visitor pattern is ideal.
However, if these classes change often, it may be better to define operations
within the classes themselves rather than using a visitor.
Implementation – Visitor Pattern
○ T
his allows the Visitor to interact directly with the interface of each specific
element type.
2. ConcreteVisitor:
ElementA
○ Each class in the object structure (like ElementB
, , etc.)
acceptm ethod.
implements an
visitm ethod.
○ This method takes a Visitor and calls the corresponding
○ S
o, which method gets executed depends onboththetype of the Visitor and
the type of the Element.
Key Concepts
○ T
his lets the program decide behavior based ontwotypes: the element and
the visitor.
● T
he structure containing the elements (like a list or tree) must ensure each element is
visited.