[go: up one dir, main page]

0% found this document useful (0 votes)
8 views94 pages

DP Full Answers

The document discusses design patterns, particularly focusing on the Model-View-Controller (MVC) pattern, which separates an application into three components: Model, View, and Controller, to enhance modularity and maintainability. It outlines various design patterns categorized into Creational, Structural, and Behavioral, detailing their purposes, structures, and applications. Additionally, it contrasts Object-Oriented Software with Design Patterns, emphasizing the importance of encapsulation, data hiding, and modifiability in object implementation.

Uploaded by

Rohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views94 pages

DP Full Answers

The document discusses design patterns, particularly focusing on the Model-View-Controller (MVC) pattern, which separates an application into three components: Model, View, and Controller, to enhance modularity and maintainability. It outlines various design patterns categorized into Creational, Structural, and Behavioral, detailing their purposes, structures, and applications. Additionally, it contrasts Object-Oriented Software with Design Patterns, emphasizing the importance of encapsulation, data hiding, and modifiability in object implementation.

Uploaded by

Rohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

‭UNIT-1‬

‭ 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.‬

‭1. Pattern Name and Classification‬


‭●‬ ‭What‬‭: Unique name + category (Creational, Structural, Behavioral).‬

‭●‬ ‭Why‬‭: Aids quick identification and developer communication.‬

‭2. Intent / Also Known As‬

‭●‬ ‭What‬‭: Purpose of the pattern + alternate names.‬

‭●‬ ‭Why‬‭: Clarifies the problem it solves and its variations in naming.‬

‭3. Motivation‬

‭●‬ ‭What‬‭: Real-world scenario showing the need for this pattern.‬

‭●‬ ‭Why‬‭: Makes the pattern relatable and meaningful.‬

‭4. Applicability‬

‭●‬ ‭What‬‭: When to use the pattern.‬

‭●‬ ‭Why‬‭: Helps you pick the right pattern at the right time.‬

‭5. Structure‬

‭●‬ ‭What‬‭: UML-like diagram showing class relationships.‬

‭●‬ ‭Why‬‭: Visual blueprint of how components fit together.‬

‭6. Participants‬

‭●‬ ‭What‬‭: Key classes/objects involved and their roles.‬

‭●‬ ‭Why‬‭: Shows "who does what" in the pattern.‬

‭7. Collaborations‬

‭●‬ ‭What‬‭: How participants interact at runtime.‬

‭●‬ ‭Why‬‭: Reveals the dynamic flow of communication.‬

‭8. Consequences‬
‭●‬ ‭What‬‭: Benefits and drawbacks of using the pattern.‬

‭●‬ ‭Why‬‭: Helps you evaluate trade-offs.‬

‭9. Implementation‬

‭●‬ ‭What‬‭: Tips, pitfalls, and techniques for coding the pattern.‬

‭●‬ ‭Why‬‭: Bridges theory and real-world coding.‬

‭10. Sample Code‬

‭●‬ ‭What‬‭: Concrete code example (e.g., Java, Python).‬

‭●‬ ‭Why‬‭: Helps translate the pattern into your own project.‬

‭11. Known Uses‬

‭●‬ ‭What‬‭: Real-world implementations of the pattern.‬

‭●‬ ‭Why‬‭: Builds confidence and offers inspiration.‬

‭12. Related Patterns‬

‭●‬ ‭What‬‭: Patterns that complement or contrast with it.‬

‭●‬ ‭Why‬‭: Encourages deeper pattern literacy.‬

‭catalog of design patterns ?‬


‭🔨 Creational Patterns‬
‭Focus: Object creation logic.‬

‭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).‬

‭●‬ ‭Prototype‬‭: Creates new objects by copying an existing object (clone).‬

‭●‬ ‭Singleton‬‭: Ensures a class has only one instance and provides global access to it.‬

‭🧱 Structural Patterns‬
‭Focus: How classes/objects are composed.‬

‭Class Scope‬

‭●‬ ‭Adapter‬‭: Converts one interface into another expected by clients.‬


‭Object Scope‬

‭●‬ ‭Adapter‬‭: Wraps an object to provide a different interface.‬

‭●‬ ‭Bridge‬‭: Decouples abstraction from implementation.‬

‭●‬ ‭Composite‬‭: Composes objects into tree structures (e.g., menus, UI elements).‬

‭●‬ ‭Decorator‬‭: Adds responsibilities to objects dynamically.‬

‭●‬ ‭Facade‬‭: Provides a simplified interface to a complex subsystem.‬

‭●‬ ‭Proxy‬‭: Acts as a placeholder or control access to another object.‬

‭🤖 Behavioral Patterns‬
‭Focus: Communication between objects.‬

‭Class Scope‬

‭●‬ ‭Interpreter‬‭: Defines a grammar and interpreter for language expressions.‬

‭●‬ T
‭ emplate Method‬‭: Defines a skeleton of an algorithm, allowing subclasses to‬
‭override specific steps.‬

‭Object Scope‬

‭●‬ ‭Chain of Responsibility‬‭: Passes request along a chain of handlers.‬

‭●‬ ‭Command‬‭: Encapsulates a request as an object.‬

‭●‬ ‭Iterator‬‭: Provides a way to access elements of a collection sequentially.‬

‭●‬ ‭M ediator‬‭: Centralizes complex communication between objects.‬

‭●‬ ‭M emento‬‭: Captures and restores an object’s internal state.‬

‭●‬ ‭Flyweight‬‭: Shares objects to reduce memory usage.‬

‭●‬ ‭O bserver‬‭: Notifies dependent objects about changes.‬

‭●‬ ‭State‬‭: Changes behavior based on internal state.‬

‭●‬ ‭Strategy‬‭: Encapsulates interchangeable algorithms.‬


‭●‬ ‭Visitor‬‭: Adds new operations without modifying object structure.‬

‭ ow Design Patterns Solve Design Problems:?‬


H
‭[Also Check the pdf Answer]‬

‭a) Finding Appropriate Objects‬

I‭dentify the right set of‬‭objects‬‭and their‬‭responsibilities‬‭. It’s about breaking down the‬
‭problem domain into classes that reflect real-world entities and operations.‬

‭💡 ‬‭Design patterns like MVC (Model-View-Controller) help divide responsibilities clearly.‬

‭b) Determining Object Granularity‬

‭Decide‬‭how many objects‬‭you need and how "fine-grained" each object should be.‬

‭●‬ ‭Too fine‬‭: Makes the system complex and hard to manage.‬

‭●‬ ‭Too coarse‬‭: Leads to inflexible or monolithic systems.‬

‭💡 ‬‭Composite and Flyweight patterns help manage granularity.‬

‭c) Specifying Object Interfaces‬

‭Design clear‬‭interfaces‬‭for objects, defining how they interact with other parts of the system.‬

💡
‭ ‬‭Patterns like Strategy, Observer, and Command depend heavily on well-defined‬
‭interfaces.‬

‭d) Specifying Object Implementations‬

‭ etermine‬‭how‬‭an object fulfills its responsibilities. This involves selecting data structures,‬
D
‭algorithms, and internal logic.‬
‭💡 ‬‭Encapsulation and hiding internal implementation details are key here.‬

‭e) Class versus Interface Inheritance‬

‭ ecide whether to‬‭inherit from classes‬‭(implementation inheritance) or from‬‭interfaces‬


D
‭(pure abstraction).‬

‭●‬ ‭Class inheritance‬‭s hares behavior but tightly couples classes.‬

‭●‬ ‭Interface inheritance‬‭promotes flexibility and multiple inheritance.‬

‭💡 ‬‭M any design patterns encourage interface-based design (e.g., Bridge, Strategy).‬

‭f) Programming to an Interface, Not an Implementation‬

‭ rite code that depends on‬‭abstractions‬‭(interfaces), not concrete classes. This makes‬
W
‭c ode‬‭flexible‬‭and‬‭e asier to change‬‭.‬

‭💡 ‬‭Use‬‭
Shape‬‭instead of‬‭
Circle‬‭or‬‭
Rectangle‬‭directly.‬

/‭/ BAD‬
‭Circle c = new Circle();‬

/‭/ GOOD‬
‭Shape s = new Circle();‬

‭g) Putting Reuse Mechanisms to Work‬

‭Choose between‬‭inheritance‬‭and‬‭composition‬‭for code reuse:‬

‭●‬ ‭Inheritance‬‭: Reuse behavior from parent classes.‬

‭●‬ ‭Composition‬‭: Reuse behavior by containing other objects.‬

‭💡 ‬‭Patterns like Decorator and Strategy use composition.‬

‭h) Inheritance versus Composition / Delegation‬


‭●‬ ‭Inheritance‬‭: “Is-a” relationship (tight coupling).‬

‭●‬ ‭Composition‬‭: “Has-a” relationship (more flexible).‬

‭●‬ ‭Delegation‬‭: One object delegates behavior to another.‬

‭💡 ‬‭Prefer composition over inheritance for flexibility and maintainability.‬

‭i) Relating Run-Time and Compile-Time Structures‬

‭●‬ ‭Compile-time‬‭: Class hierarchy (known before running).‬

‭●‬ ‭Run-time‬‭: Actual object structure and relationships during execution.‬

‭💡 ‬‭Use patterns like Factory or Proxy to control runtime structures dynamically.‬

‭j) Designing for Change‬

‭ esign your code so that it's‬‭e asy to extend‬‭and‬‭modify‬‭without breaking existing‬


D
‭functionality.‬

‭ ‬‭O pen/Closed Principle‬‭: Open for extension, closed for modification. 💡 ‬‭Patterns like‬
💡
‭Strategy, Observer, and State support changeable behavior.‬

‭k) Application Programs‬

‭ ustom-built software tailored for a specific need. Design patterns help‬‭organize‬‭the‬


C
‭s tructure and behavior of such applications.‬

‭💡 ‬‭Use patterns like MVC in application development to separate concerns.‬

‭l) Toolkits‬

‭Reusable‬‭collections of classes and functions‬‭used across different applications.‬

💡
‭ ‬‭Design patterns help build generic, reusable components (e.g., using Template Method or‬
‭Abstract Factory in a GUI toolkit).‬
‭m) Frameworks‬

‭ ‬‭semi-complete application‬‭s tructure that can be customized by plugging in your own‬


A
‭c ode.‬

💡
‭ ‬‭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‬‭:‬

‭🔹 Object-Oriented Software (OOS):‬


‭Aspect‬ ‭Description‬
‭Definition‬ A
‭ software system built using the principles of‬‭O bject-Oriented‬
‭Programming (OOP)‬‭— such as‬‭classes, objects, inheritance,‬
‭e ncapsulation, and polymorphism‬‭.‬

‭Purpose‬ ‭ o structure software as a collection of interacting objects that model‬


T
‭real-world entities.‬

‭Focus‬ ‭ ode structure, class relationships, and reuse through‬


C
‭inheritance/composition.‬

‭Example‬ Student‬
‭A student management system with‬‭ Teacher‬
‭,‬‭ Course‬‭c lasses.‬
‭,‬‭

‭🔹 Design Patterns:‬
‭Aspect‬ ‭Description‬

‭Definition‬ A
‭ ‬‭reusable solution‬‭to a common design problem that occurs within a‬
‭particular context in software design. Design patterns are‬‭blueprints‬‭or best‬
‭practices, not actual code.‬

‭Purpose‬ ‭ o‬‭solve recurring design problems‬‭and improve software architecture‬


T
‭using proven approaches.‬

‭Focus‬ I‭nteraction between classes/objects at a higher design level. Promotes‬


‭flexibility, reusability, and maintainability.‬

‭Example‬ ‭ sing the‬‭O bserver Pattern‬‭s o that multiple components update‬


U
‭automatically when one changes (e.g., in a news feed app).‬

‭✅ Key Differences in Summary:‬


‭O bject-Oriented Software‬ ‭Design Patterns‬

‭Based on OOP concepts‬ ‭Based on reusable design solutions‬

‭Focuses on modeling real-world entities‬ ‭Focuses on solving design problems‬

‭Deals with how software is built‬ ‭Deals with how software is designed‬

‭Involves implementation‬ ‭O ften abstract and language-independent‬

‭Example: Using classes and objects‬ ‭Example: Singleton, Factory, Observer‬


‭Brief Description of Object Implementations:‬
‭ bject Implementation‬‭refers to how the internal behavior and data of an object are defined‬
O
‭and managed behind the scenes in a software program. It's about‬‭how an object does what‬
‭it’s supposed to do‬‭.‬

‭🔹 Key Points:‬

‭1.‬ ‭Encapsulation‬

‭○‬ ‭O bject implementation hides internal data and logic.‬

‭○‬ ‭O nly allows access through‬‭methods (functions)‬‭.‬

‭2.‬ ‭Attributes and Methods‬

‭○‬ ‭Attributes (also called fields or properties) store the‬‭state‬‭.‬

‭○‬ ‭Methods define the‬‭behavior‬‭.‬

‭3.‬ ‭Data Hiding‬

‭○‬ I‭mplementation 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)‬

‭public void setSpeed(int s) { // method (public interface)‬


‭if(s > 0) {‬
‭s peed = s;‬
‭}‬
‭}‬

‭public int getSpeed() {‬


‭return speed;‬
‭}‬
‭}‬

‭5.‬
setSpeed()‬‭and‬‭
‭○‬ ‭The user interacts with‬‭ getSpeed()‬‭but does not know‬
speed‬‭is internally stored or validated.‬
‭how‬‭

‭🔹 In Design Patterns:‬

‭In design patterns,‬‭object implementation‬‭is important because:‬

‭●‬ P
‭ atterns like‬‭Strategy‬‭,‬‭Decorator‬‭, or‬‭Bridge‬‭help separate the interface from the‬
‭implementation.‬

‭●‬ ‭This makes the code more‬‭flexible‬‭and‬‭e xtendable‬‭.‬


‭UNIT-2‬

‭ iscuss about Lexi’s user interface‬


D
‭and its design Problem ?‬
‭Lexi’s User Interface and Its Design Problem‬
‭ ase study in the design of a "What-You-See-Is-What-You-Get" (or "WYSIWYG") document‬
c
‭editor called‬‭Lexi‬‭.‬

‭ exi is a document editor, and like any modern editor, it needs a‬‭flexible and efficient user‬
L
‭interface‬‭to handle different elements like text, images, graphics, and windows. The‬
‭c hallenge in designing Lexi’s UI comes from‬‭the need to support multiple windowing‬
‭systems, ensure flexibility, and maintain an efficient layout.‬

‭1. The Design Problem‬

‭1. Document Structure‬


‭‬ L
● ‭ exi needs a flexible way to represent text, images, and graphics in a document.‬
‭●‬ ‭The structure should allow for‬‭hierarchical organization‬‭(e.g., paragraphs inside‬
‭s ections, text inside paragraphs).‬
‭●‬ ‭Solution:‬
‭○‬ ‭The‬‭Composite Pattern‬‭is used to treat all document elements (characters,‬
‭words, images) as‬‭G lyphs‬‭, allowing complex nesting and uniform handling.‬

‭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 Pattern‬‭enables applying formatting styles dynamically without‬
‭m odifying the core document structure.‬

‭3. Embellishing the User Interface‬


‭●‬ L ‭ exi must support UI enhancements like scrollbars, borders, and decorations around‬
‭text.‬
‭●‬ ‭These embellishments should be optional and independent of the core document‬
‭s tructure.‬
‭●‬ ‭Solution:‬
‭○‬ ‭The‬‭Decorator Pattern‬‭allows adding embellishments like borders and‬
‭s crollbars without modifying the document's main content.‬

‭4. Supporting Multiple Look-and-Feel Standards‬


‭●‬ T ‭ he UI should be adaptable to different themes and styles (e.g., Windows, MacOS,‬
‭c ustom themes).‬
‭●‬ ‭Users should be able to switch styles‬‭without rewriting‬‭the entire UI.‬
‭●‬ ‭Solution:‬
‭○‬ ‭Abstract Factory Pattern‬‭helps in creating UI components based on the‬
‭s elected theme dynamically.‬

‭5. Supporting Multiple Window Systems‬


‭●‬ L ‭ exi should work across different operating systems with varying window‬
‭m anagement APIs.‬
‭●‬ ‭Instead of creating separate implementations for each OS, Lexi needs an abstraction.‬
‭●‬ ‭Solution:‬
‭○‬ ‭The‬‭Bridge Pattern‬‭s eparates‬‭high-level window operations‬‭from‬
‭low-level system-specific implementations‬‭, making the system portable.‬

‭6. User Operations‬


‭●‬ U ‭ sers should be able to‬‭undo/redo actions, cut/copy/paste text‬‭, and perform other‬
‭operations efficiently.‬
‭●‬ ‭These operations must be recorded and executed dynamically.‬
‭●‬ ‭Solution:‬
‭○‬ ‭The‬‭Command Pattern‬‭encapsulates user actions (like delete, copy) into‬
‭objects, allowing‬‭undo/redo‬‭functionalities.‬
‭Supporting Multiple Window Systems:‬

‭Problem: Different Window Systems‬


‭●‬ D ‭ ifferent operating systems have different ways (APIs) to create and manage‬
‭windows.‬
‭●‬ ‭You want your application (Lexi) to work on multiple systems without rewriting‬
‭window-related code for each one.‬

‭W hy Not Use Abstract Factory?‬


‭‬ A
● ‭ n‬‭Abstract Factory‬‭is used to create families of related objects.‬
‭●‬ ‭But in this case, window systems have very different APIs, so an Abstract Factory‬
‭isn’t the best fit.‬
‭●‬ ‭Instead, we need a‬‭common interface‬‭that works across different window systems.‬

‭Solution: Window & WindowImp (Bridge Pattern)‬


‭●‬ W ‭ indow class (Abstraction)‬‭: Defines a general interface that all windows should‬
‭have (e.g., Redraw, Resize, DrawLine).‬
‭●‬ ‭WindowImp class (Implementation)‬‭: Handles the actual window operations for a‬
‭s pecific system (e.g., Mac, Windows, X11).‬

‭How It Works‬

‭1.‬ T ‭ he‬‭Window class‬‭has general operations like‬‭Redraw()‬ Iconify()‬


‭,‬‭ ‭, and‬
DrawLine()‬
‭ ‭.‬
‭2.‬ ‭It delegates system-specific tasks to‬‭WindowImp‬‭, which implements them differently‬
‭for Mac, Windows, or another OS.‬
‭3.‬ ‭This separation allows Lexi to work on multiple operating systems by simply swapping‬
‭out the appropriate‬‭WindowImp‬‭without modifying the‬‭Window‬‭c lass.‬
‭i) Spelling Checking‬
‭ efinition‬‭:‬
D
‭Spelling checking is a feature in word processors or text editors that automatically‬‭detects‬
‭and highlights incorrect spellings‬‭in the text.‬

‭How it works‬‭:‬

‭●‬ ‭It compares each word to a built-in dictionary.‬

‭●‬ ‭Misspelled words are often underlined in red.‬

‭●‬ ‭Users are given suggestions to correct the word.‬

‭ xample‬‭:‬
E
‭If you type “recieve”, the spell checker will highlight it and suggest “receive”.‬

‭ii) Hyphenation‬

‭ efinition‬‭:‬
D
‭Hyphenation is the process of‬‭breaking words between lines using hyphens (-)‬‭to‬
‭improve text layout and alignment, especially in justified text.‬

‭Purpose‬‭:‬

‭●‬ ‭Avoid large spaces in justified paragraphs.‬

‭●‬ ‭Make the document more readable and professionally formatted.‬

‭ 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)‬

‭ . Consider any application of Case study? How to support the Document‬


7
‭editor design patterns?‬

‭Case Study: Collaborative Document Editor (e.g., Google Docs)‬

‭ 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.‬

‭This approach enhances functionality and maintainability.‬

‭8. Write Short Notes on Design a Document Editor?‬

‭●‬ 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.‬

‭ hat is meant by intersection of functionality and union of functionality?‬


W
‭Explain ?‬

‭ reat question! Let's break down the concepts of‬‭intersection of functionality‬‭and‬‭union‬


G
‭of functionality‬‭in a simple and clear way:‬

‭1. Intersection of Functionality‬

‭✅ Meaning:‬

‭ he‬‭intersection of functionality‬‭refers to the‬‭common features or behaviors shared‬‭by‬


T
‭different classes or components in a system.‬

‭📌 Think of it like this:‬

I‭f two or more modules have some‬‭overlapping functionality‬‭, that shared part is the‬
‭intersection‬‭.‬

‭💡 Example:‬

‭Imagine you have two classes:‬

‭●‬ ‭
Printer‬

‭●‬ ‭
Scanner‬

‭ oth might have a function like‬‭


B connectToDevice()‬‭— this shared method is part of their‬
‭intersection of functionality‬‭.‬

‭📊 In Set Theory:‬

‭If A = {print, connect} and B = {scan, connect}, then:‬


‭●‬ ‭Intersection (A ∩ B)‬‭= {connect}‬

‭2. Union of Functionality‬

‭✅ Meaning:‬

‭ he‬‭union of functionality‬‭refers to‬‭all the features or capabilities‬‭c ombined from multiple‬


T
‭c lasses or modules — whether they are common or unique.‬

‭📌 Think of it like this:‬

‭It represents the‬‭complete set of functionalities‬‭a system might need or provide.‬

‭💡 Example:‬

‭Using the same example:‬

‭●‬ ‭
Printer‬‭has: {print, connect}‬

‭●‬ ‭
Scanner‬‭has: {scan, connect}‬

‭Then:‬

‭●‬ ‭Union (A ∪ B)‬‭= {print, scan, connect}‬

‭🧠 Why It’s Useful?‬

‭●‬ I‭ntersection‬‭helps in identifying‬‭what can be abstracted or reused‬‭(like via‬


‭interfaces or base classes).‬

‭●‬ ‭Union‬‭helps in understanding the‬‭total capability‬‭required or provided by a system.‬

‭🔧 Use in Software Design:‬

‭Term‬ ‭Use Case‬


‭Intersection‬ ‭To define‬‭interfaces‬‭,‬‭abstract classes‬‭, or‬‭shared behavior‬

‭Union‬ ‭To design‬‭composite components‬‭,‬‭frameworks‬‭, or‬‭full features‬‭s et‬

‭ xample in‬
E ‭ trategy pattern focuses on the‬‭common interface‬‭(intersection), while‬
S
‭Design‬ ‭a framework might provide the‬‭full range‬‭(union)‬
‭UNIT_3‬
‭Abstract Factory Pattern ?‬
‭Applicability:‬
‭Use the Abstract Factory Pattern when:‬

‭●‬ A
‭ system should be‬‭independent of how its products are created, composed,‬
‭and represented‬‭.‬

‭●‬ ‭A system should be configured with‬‭multiple families of products‬‭.‬

‭●‬ ‭You want to‬‭e nforce consistency among products‬‭from the same family.‬

‭●‬ ‭You want to hide the product implementations and expose only interfaces.‬

‭Consequences (Benefits):‬
‭●‬ ‭Isolation‬‭of concrete classes.‬

‭●‬ ‭Easier to swap product families‬‭.‬

‭●‬ ‭Promotes consistency‬‭among products.‬

‭●‬ ‭Supports‬‭product variants‬‭and‬‭plugin architectures‬‭.‬

‭Related Patterns:- •‬

‭Factory Method -- a ―virtual‖ constructor •‬

‭Prototype -- asks productsto clone themselves •‬

‭Singleton -- allows creation of only a single instance‬


‭Consequences of Builder Pattern‬

‭ 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:‬

‭1.‬ I‭ ncreased Complexity‬‭:‬


‭The pattern requires creating multiple classes (Builder, Director, Product), which can‬
‭increase the complexity of the codebase.‬
‭1.‬ O
‭ verhead for Simple Objects‬‭:‬
‭For simple objects that do not require a complex construction process, using the Builder‬
‭Pattern may be overkill.‬
‭1.‬ R
‭ untime Errors‬‭:‬
‭If the construction process is not properly defined or steps are missed, it may lead to runtime‬
‭errors or incomplete objects.‬
‭ ist and explain the implementation issues‬
L
‭of factory method ?‬
‭UNIT-4‬

‭ otivation:‬
M
‭The Adapter pattern lets you‬‭integrate incompatible interfaces‬‭without modifying their‬
‭s ource code. It provides a‬‭bridge between old and new systems‬‭, promoting‬‭reusability‬
‭and‬‭flexibility‬‭in your software design.‬
‭2. a) Uses and Related Patterns of Bridge Design Pattern‬

‭Uses of Bridge Pattern:‬

‭1.‬ ‭Decouples abstraction from implementation‬‭s o both can evolve independently.‬

‭2.‬ ‭Improves code maintainability‬‭by separating concerns.‬

‭3.‬ H
‭ elps avoid class explosion‬‭(when every combination of abstraction and‬
‭implementation leads to a new subclass).‬

‭4.‬ ‭Allows runtime binding‬‭of implementation classes.‬

‭5.‬ ‭Ideal when:‬

‭○‬ ‭You need to vary abstraction and implementation‬‭independently‬‭.‬

‭○‬ ‭You want to‬‭change implementations without affecting clients‬‭.‬

‭🔗 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.‬

‭2. b) What is Bridge Pattern? Explain the Functions of Each‬

‭Definition:‬

‭ he‬‭Bridge Pattern‬‭is a‬‭structural design pattern‬‭that splits a large class or a‬


T
‭c losely related set of classes into two separate‬‭hierarchies‬‭—abstraction and‬
‭implementation—which can be developed‬‭independently‬‭.‬

‭Key Components and Their Functions:‬


‭Component‬ ‭Function‬

‭Abstraction‬ ‭ efines the‬‭interface‬‭for the client; holds a reference to the‬


D
Implementor‬
‭ ‭.‬

‭Refined Abstraction‬ ‭ xtends the Abstraction and‬‭customizes‬‭it (e.g., a specific type of‬
E
‭abstraction).‬

‭Implementor‬ ‭Defines the‬‭interface‬‭for the implementation classes.‬

‭ oncrete‬
C ‭Implements the Implementor interface with‬‭specific behavior‬‭.‬
‭Implementor‬
‭Composite Design Pattern‬
‭Known Uses:‬

Window‬‭c ontains Panels, which contain Buttons, Labels, etc.‬


‭●‬ ‭G UI libraries:‬‭A‬‭

‭●‬ ‭File systems:‬‭Files and directories (directories contain other files/directories).‬

‭●‬ ‭XML/HTML parsers:‬‭Nodes containing text or child nodes.‬

‭●‬ ‭G ame Engines:‬‭Game objects may contain child game objects.‬


‭🔗 Related Patterns:‬
‭ elated‬
R ‭How It's Related‬
‭Pattern‬

‭Decorator‬ ‭ lso involves recursive structures, but adds behavior rather than‬
A
‭c omposition.‬

‭Flyweight‬ ‭Can be combined with Composite to share components.‬

‭Iterator‬ ‭Useful for traversing a composite structure.‬

‭Visitor‬ ‭ an be used to define new operations on composite structures without‬


C
‭c hanging them.‬
‭🤝 Collaboration:‬

‭●‬ ‭Component‬‭defines the interface for objects that can have added responsibilities.‬

‭●‬ ‭ConcreteComponent‬‭is the original object whose behavior we want to extend.‬

‭●‬ D
‭ ecorator‬‭m aintains a reference to a Component object and implements the‬
‭Component interface.‬

‭●‬ C
‭ oncreteDecorator‬‭adds new behavior before/after delegating work to the‬
‭Component object it wraps.‬

📌
‭ The decorator wraps the component and forwards requests to it, potentially adding‬
‭behavior‬‭before or after‬‭the forwarding.‬
‭🌍 Known Uses:‬
‭Java I/O Streams‬

‭ .‬
1
‭2.‬ ‭G UI Libraries‬

ScrollDecorator‬‭adds scrolling to a text view.‬


‭○‬ ‭A‬‭

BorderDecorator‬‭adds a border to a component.‬


‭○‬ ‭A‬‭

‭3.‬ ‭M iddleware / Logging‬

‭○‬ ‭W rap a service to add logging or security behavior.‬

‭4.‬ ‭Compression/Encryption Wrappers‬

‭○‬ ‭W rap file streams with encryption or compression.‬

‭🔗 Related Patterns:‬
‭Pattern‬ ‭Relation to Decorator‬

‭Adapter‬ ‭ hanges interface; Decorator maintains interface but adds‬


C
‭behavior.‬

‭Composite‬ ‭ ecorator can be used in composite structures to add behavior to‬


D
‭c omponents.‬

‭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.‬

‭Strategy‬ ‭ trategy changes the internal logic/algorithm, Decorator adds‬


S
‭features dynamically.‬
‭✅ Consequences of the Façade Pattern‬

‭1.‬ ‭Simplifies usage of complex subsystems‬

‭○‬ I‭t hides the complexities of the subsystem and provides a cleaner,‬
‭easier-to-use interface.‬

‭2.‬ ‭Reduces client-subsystem coupling‬

‭○‬ C
‭ lients interact with the facade instead of multiple subsystem classes directly.‬
‭This promotes‬‭loose coupling‬‭.‬

‭3.‬ ‭Improves code readability and maintainability‬

‭○‬ W
‭ ith a simplified interface, the overall readability of code increases, especially‬
‭when many operations are bundled.‬

‭4.‬ ‭Does not prevent access to subsystem classes‬

‭○‬ C
‭ lients can still use subsystem classes if needed. The pattern doesn’t restrict‬
‭direct access.‬

‭5.‬ ‭Supports layering‬


‭○‬ I‭t helps in creating system layers, where the facade acts as a boundary‬
‭between the client and complex subsystems.‬

‭6.‬ ‭Helps minimize compilation dependencies‬

‭○‬ C
‭ hanges in the subsystem might not affect the clients, reducing the need for‬
‭recompilation.‬

‭🛠️ Implementation Issues‬

‭1.‬ ‭Reducing Client-Subsystem Coupling‬

‭○‬ U Facade‬‭c lass so the implementation can‬


‭ se‬‭abstraction‬‭: Define an abstract‬‭
‭be changed without affecting the client.‬

‭○‬ O
‭ r use‬‭composition‬‭: Inject or configure subsystem objects inside the Facade‬
‭to allow flexibility.‬

‭2.‬ ‭Customizing the Facade‬

‭○‬ F
‭ acade class can be customized or extended by replacing some of the‬
‭s ubsystem objects.‬

‭3.‬ ‭Public vs. Private Subsystem Classes‬

‭○‬ S
‭ ubsystems may expose some classes publicly (used by clients) and keep‬
‭others private (used internally).‬

‭○‬ F
‭ açade is a part of the‬‭public API‬‭; private subsystem classes are used only‬
‭within the module or library.‬

‭4.‬ ‭Choosing the Right Responsibilities‬

‭○‬ ‭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‬

I‭magine you’re designing a text editor like MS Word.‬


‭Each character (letter, punctuation, etc.) on the screen is an object. If a document has 1‬
‭m illion characters, and each character is a separate object with its own font, size, position,‬
‭etc., that’s a‬‭huge memory‬‭load.‬

‭However, most of this data is‬‭shared‬‭:‬

‭●‬ ‭The‬‭glyph‬‭(shape of a letter) like 'a', 'b', 'c' is common.‬

‭●‬ ‭W hat varies is the‬‭position‬‭of the character, maybe its‬‭style‬‭(bold, italic) or‬‭color‬‭.‬

‭So, instead of creating 1 million full objects, we:‬

‭●‬ ‭Create a‬‭single shared object per character‬‭(like a shared 'a', 'b', etc.)‬

‭●‬ ‭Pass‬‭e xternal state‬‭like position and formatting when needed.‬

‭This drastically‬‭reduces memory usage‬‭and‬‭improves performance‬‭.‬


I‭magine you have a‬‭huge image file‬‭you want to display in an app. Loading that image every‬
‭time is expensive and slow.‬

‭Instead of creating the real image every time:‬

‭●‬ ‭You create a‬‭proxy‬‭object that looks like the image.‬

‭●‬ ‭W hen the image is needed (like on display), the proxy loads it‬‭lazily‬‭.‬

‭This is useful for:‬

‭●‬ ‭Lazy initialization‬‭(load only when needed)‬

‭●‬ ‭Access control‬‭(protect access to sensitive objects)‬

‭●‬ ‭Logging / auditing‬‭(record usage)‬

‭●‬ ‭Remote proxy‬‭(stand-in for objects on a network)‬

‭●‬ ‭Caching‬‭(return a stored result instead of recalculating)‬


‭Participants in Proxy Pattern‬

‭1.‬ ‭Subject (Interface or Abstract Class)‬

‭○‬ D
‭ efines the‬‭common interface‬‭for‬‭RealSubject‬‭and‬‭Proxy‬‭s o that a proxy‬
‭c an be used wherever a real object is expected.‬

Image‬‭interface with method‬‭


‭○‬ ‭Example:‬‭ display()‬

‭2.‬ ‭RealSubject‬

‭○‬ ‭The actual object that does the real work.‬

‭○‬ C
‭ lients ultimately want to interact with this, but it may be expensive or‬
‭restricted.‬

RealImage‬‭c lass that loads and displays an image.‬


‭○‬ ‭Example:‬‭
‭3.‬ ‭Proxy‬

‭○‬ ‭Maintains a reference to the‬‭RealSubject‬‭.‬

‭○‬ ‭Controls access to the RealSubject.‬

‭○‬ ‭Responsible for tasks like lazy loading, logging, security, or remote access.‬

ImageProxy‬‭c lass that implements‬‭


‭○‬ ‭Example:‬‭ Image‬‭and manages‬
RealImage‬
‭ ‭.‬

‭4.‬ ‭Client‬

‭○‬ U
‭ ses the‬‭Subject‬‭interface to interact with the real object through the proxy,‬
‭without knowing whether it's talking to a proxy or the actual object.‬

‭✅ Consequences of Proxy Pattern:‬

‭●‬ ‭Introduces a level of‬‭indirection‬‭in accessing an object.‬

‭●‬ ‭Depending on the type, proxy provides various benefits:‬

‭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.‬

‭●‬ ‭Copy-on-Write Optimization‬‭:‬

‭○‬ ‭Useful for large objects.‬

‭○‬ ‭The proxy delays copying until modification is requested.‬

‭○‬ U
‭ ses‬‭reference counting‬‭and only copies when needed, saving memory and‬
‭time.‬

‭⚙️ Implementation Issues:‬


‭1.‬ ‭Language Support‬‭:‬

operator->‬‭to add behavior during member access.‬


‭○‬ ‭C++‬‭: Use‬‭

‭○‬ S doesNotUnderstand:‬‭to forward unrecognized‬


‭ malltalk‬‭: Override‬‭
‭m essages.‬

‭2.‬ ‭Abstract Interfaces‬‭:‬

‭○‬ P
‭ roxies can work through abstract interfaces to avoid knowing the exact type‬
‭of the real subject.‬

‭○‬ ‭If instantiating the real object, type knowledge is required.‬

‭3.‬ ‭Subject Referencing‬‭:‬

‭○‬ ‭Proxy must manage references to subjects whether in memory or disk.‬

‭○‬ ‭Use‬‭address-independent identifiers‬‭to refer to them before instantiation.‬


‭UNIT-5‬

‭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‬

I‭magine 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:‬

‭●‬ ‭A‬‭chain‬‭is formed with potential handlers.‬

‭●‬ ‭The request is passed along the chain until a suitable handler is found.‬

‭This increases‬‭flexibility‬‭and‬‭reduces tight coupling‬‭between sender and receiver.‬

‭ 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:‬

‭ he‬‭Command pattern‬‭turns a request into a stand-alone‬‭object (called a‬‭c ommand‬‭),‬


T
‭allowing you to:‬

‭●‬ ‭Parameterize clients with different requests,‬

‭●‬ ‭Q ueue or log requests,‬

‭●‬ ‭Support undo/redo operations.‬

‭🚀 Motivation:‬

‭Imagine a‬‭remote control‬‭for a smart home. You can‬‭press a button to:‬

‭●‬ ‭Turn on the light,‬


‭●‬ ‭Turn off the fan,‬

‭●‬ ‭Start the coffee machine...‬

‭ ach button sends a‬‭command‬‭, but the remote doesn’t‬‭need to know‬‭how‬‭those devices‬
E
‭work internally.‬
➡️
‭ It just sends the right command to the right device.‬

‭This decouples the‬‭invoker (remote control)‬‭from the‬‭receiver (device)‬‭.‬

‭📌 Use Cases:‬

‭●‬ ‭Undo/Redo operations‬

‭●‬ ‭Transaction-based systems‬

‭●‬ ‭Macro recording‬

‭●‬ ‭Q ueuing tasks‬

‭🔁 Related Patterns:‬

‭●‬ ‭M emento‬‭– for undo functionality‬

‭●‬ ‭Composite‬‭– for macro commands (multiple commands together)‬

‭●‬ ‭O bserver‬‭– if commands need to notify others‬

‭Implementation Issues‬

‭1.‬ ‭Implementing the Successor Chain‬

Handler‬‭c lass).‬
‭○‬ ‭Can be done by adding explicit links (usually in the‬‭

‭○‬ ‭Alternatively, use existing object references if available.‬

‭2.‬ ‭Connecting Successors‬


Handler‬‭to maintain the chain and define‬
‭○‬ I‭f no links exist, introduce them in‬‭
‭the interface.‬

‭3.‬ ‭Representing Requests‬


‭○‬ ‭Use:‬

‭■‬ ‭Fixed method calls‬‭(simple and type-safe).‬

‭■‬ ‭O r a‬‭generic handler function‬‭with request codes (more flexible).‬

‭4.‬ ‭Automatic Forwarding (Smalltalk)‬


doesNotUnderstand‬‭c an catch unhandled messages and‬
‭○‬ ‭Smalltalk’s‬‭
‭forward them to the next handler.‬

‭✅ Applicability‬

‭Use the‬‭Command pattern‬‭when you want to:‬

‭●‬ ‭Parameterize objects‬‭with actions to perform (like‬‭c allbacks, but object-oriented).‬

‭●‬ ‭Q ueue, log, or schedule‬‭requests for later execution.‬

‭●‬ ‭Support undo/redo‬‭functionality:‬

execute()‬‭and‬‭
‭○‬ ‭Commands can implement‬‭ unexecute()‬‭(or‬‭
undo()‬
‭).‬

‭○‬ ‭Maintain a history list of executed commands.‬

‭○‬ ‭Traverse the list to undo/redo.‬

‭●‬ ‭Log commands‬‭for crash recovery:‬

‭○‬ ‭Log can be replayed by re-executing commands.‬

‭●‬ ‭Structure systems using transactions‬‭:‬

‭○‬ ‭Commands encapsulate high-level operations built from primitives.‬

‭○‬ ‭Easy to add new transactions with the common command interface.‬
‭🤝 Collaborations‬

‭●‬ C
‭ lient‬
ConcreteCommand‬‭and sets its receiver.‬
‭→ Creates‬‭

‭●‬ I‭nvoker‬
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. The‬‭Iterator‬
C
‭pattern allows‬‭uniform access‬‭to elements in these‬‭c ollections without needing to know their‬
‭s tructure.‬

‭For example:‬

‭java‬

List<String> names = new ArrayList<>();‬


Iterator<String> it = names.iterator();‬

while (it.hasNext()) {‬

System.out.println(it.next());‬

}‬

names‬‭is an‬‭
‭You don’t need to know whether‬‭ ArrayList‬ LinkedList‬
‭,‬‭ ‭, etc.‬
‭Applicability‬

‭Use the Iterator pattern when:‬

‭●‬ ‭You want to‬‭access elements‬‭of a collection without‬‭exposing its internal structure.‬

‭●‬ ‭You want to‬‭support multiple traversals‬‭(forward, backward, etc.).‬

‭●‬ ‭You want to have‬‭uniform traversal logic‬‭for different collection types.‬

‭🔧 Implementation Issues‬

‭1.‬ ‭Control of Iteration‬

‭○‬ ‭External Iterator‬‭: Client controls iteration.‬

‭○‬ ‭Internal Iterator‬‭: Iterator controls the iteration flow.‬

‭2.‬ ‭Traversal Algorithm Location‬

‭○‬ ‭Can be defined in the‬‭Iterator‬‭or‬‭Aggregate‬‭.‬


‭○‬ ‭Aggregate can use a cursor to control iteration state.‬

‭3.‬ ‭Robustness‬

‭○‬ ‭Modifying a collection during iteration may cause errors.‬

‭○‬ ‭A‬‭robust iterator‬‭avoids this without copying the‬‭c ollection.‬

‭4.‬ ‭M inimal Interface‬

First‬
‭○‬ ‭Common methods:‬‭ Next‬
‭,‬‭ IsDone‬
‭,‬‭ CurrentItem‬
‭,‬‭ ‭.‬

‭5.‬ ‭Polymorphic Iterators (C++)‬

‭○‬ R
‭ equire dynamic allocation (via factory methods), which has a performance‬
‭c ost.‬

‭6.‬ ‭Privileged Access‬

‭○‬ ‭Iterators may access aggregate internals.‬

protected‬‭m ethods or friend classes.‬


‭○‬ ‭Can be managed using‬‭

‭7.‬ ‭Composite Structures‬

‭○‬ E
‭ xternal iterators in recursive structures (like Composite pattern) must track‬
‭paths through nested elements.‬

‭8.‬ ‭Null Iterator‬

‭○‬ A
‭ "do-nothing" iterator useful for boundary conditions and simplifying traversal‬
‭logic.‬
‭Mediator Design Pattern‬

‭Intent:‬

‭●‬ T
‭ o‬‭reduce coupling‬‭between components (objects) by‬‭having them communicate‬
‭indirectly‬‭through a‬‭mediator object‬‭.‬

‭●‬ ‭Promotes‬‭loose coupling‬‭by keeping objects from referring‬‭to each other explicitly.‬

‭Motivation:‬

‭●‬ ‭In complex systems, many objects interact with each other.‬

‭●‬ ‭This leads to‬‭tight coupling‬‭and makes maintenance‬‭hard.‬

‭●‬ M
‭ ediator acts as a‬‭central controller‬‭, managing communication‬‭between‬
‭c omponents (colleagues).‬

‭●‬ E
‭ xample: In a UI, clicking a button updates a list and disables another button — all‬
‭m anaged via a‬‭dialog mediator‬‭.‬

‭Applicability:‬
‭🧠 Memento Design Pattern‬

‭✅ Intent:‬

‭●‬ C
‭ apture and externalize‬‭an object’s internal state so it can be restored later‬‭without‬
‭v iolating encapsulation‬‭.‬
‭ ere’s a trimmed and well-structured version of the‬‭Consequences‬‭and‬‭Implementation‬‭for‬
H
‭the‬‭M emento Pattern‬‭:‬

‭🧠 Memento Pattern‬
‭✅ Consequences:‬

‭1.‬ ‭Preserves Encapsulation:‬

‭○‬ ‭Internal state is saved/restored without exposing it to external objects.‬

‭2.‬ ‭Simplifies the Originator:‬

‭○‬ O
‭ riginator doesn't need to manage history or rollback logic; Memento handles‬
‭it.‬

‭3.‬ ‭Can Be Expensive:‬

‭○‬ ‭Saving full object state frequently can use lots of memory or resources.‬

‭4.‬ ‭Narrow vs. Wide Interfaces:‬

‭○‬ ‭Wide Interface‬‭(for Originator): Full access to internal‬‭s tate.‬

‭○‬ ‭Narrow Interface‬‭(for others like Caretaker): Limited‬‭or no access to state.‬

‭5.‬ ‭Hidden Costs:‬

‭○‬ M
‭ anaging many mementos (especially over time) may increase memory‬
‭usage.‬

‭○‬ ‭Must ensure old states are cleaned up or managed efficiently.‬

‭⚙️ Implementation Issues:‬

‭1.‬ ‭Language Support:‬

‭○‬ ‭You need access control to separate wide and narrow interfaces.‬

‭○‬ ‭For example:‬

friend‬‭c lasses and private members.‬


‭■‬ ‭C++‬‭: Use‬‭

‭■‬ ‭Java‬‭: Use inner classes or package-private visibility.‬

‭2.‬ ‭Storing Incremental Changes (Optimization):‬

‭○‬ ‭Instead of storing the full state, Memento can store‬‭only the changes‬‭.‬
‭○‬ ‭Useful for undoable operations like commands in a history list.‬

‭○‬ ‭Example:‬‭Text editor undo stores only the text added/removed.‬


‭Implementation:‬

‭1.‬ M
‭ apping subjects to observers‬‭: Subjects store references‬‭to observers to notify‬
‭them when necessary.‬

‭2.‬ O
‭ bserving multiple subjects‬‭: Observers may depend‬‭on multiple subjects, allowing‬
‭them to track changes from different sources.‬

‭3.‬ ‭Triggering the update‬‭:‬

Notify‬‭after its state changes.‬


‭○‬ ‭O ption 1‬‭: Subject calls‬‭

○ 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 consistent‬‭before notifying observers.‬

‭6.‬ ‭Avoiding observer-specific protocols‬‭:‬

‭○‬ ‭Push model‬‭: Subject sends detailed information to‬‭observers.‬

‭○‬ ‭Pull model‬‭: Subject sends minimal notification, and‬‭observers request details.‬

‭7.‬ S
‭ pecifying modifications of interest‬‭: Observers can‬‭register interest in specific‬
‭events, improving update efficiency.‬

‭8.‬ E
‭ ncapsulating complex update semantics‬‭: A‬‭ ChangeManager‬‭c an help manage‬
‭c omplex relationships and update strategies, reducing the need for subjects to track‬
‭observers directly.‬

‭Strategy Design Pattern‬

‭Intent‬

‭ he‬‭Strategy‬‭design pattern defines a family of algorithms,‬‭encapsulates each one, and‬


T
‭m akes them interchangeable. The pattern allows the algorithm to be selected at runtime‬
‭depending on the client's needs, thus enabling flexible behavior without modifying the context‬
‭(the object using the algorithm).‬

‭M otivation‬

‭ ometimes an object needs to perform an operation that can be implemented in multiple‬


S
‭ways, but the choice of the method may vary. Instead of using conditional statements (like‬
if-else‬‭or‬‭
‭ switch‬ ‭), the Strategy pattern allows the‬‭behavior to be encapsulated into‬
‭different strategy classes and lets the client choose which strategy to use dynamically.‬
‭Template Method Design Pattern‬

‭M otivation‬

I‭n 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.‬

‭Applicability of the Template Method Pattern‬

‭The‬‭Template Method‬‭pattern should be used in the‬‭following scenarios:‬

‭1.‬ ‭Implementing the invariant parts of an algorithm once‬‭:‬

‭○‬ I‭f 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.‬

‭2.‬ ‭Avoiding code duplication‬‭:‬

‭○‬ 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.‬

‭3.‬ ‭Refactoring existing code‬‭:‬

‭○‬ 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.‬

‭4.‬ ‭Controlling subclass extensions‬‭:‬

‭○‬ 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‬

‭1.‬ ‭Using C++ Access Control‬‭:‬

‭○‬ P protected‬‭s o‬‭they are only called by‬


‭ rimitive operations can be declared‬‭
‭the template method and not by external clients.‬

pure‬
‭○‬ ‭Primitive operations that must be overridden by subclasses should be‬‭
virtual‬
‭ ‭.‬

‭○‬ ‭The template method should be non-virtual to avoid overriding by subclasses.‬

‭2.‬ ‭M inimizing Primitive Operations‬‭:‬

‭○‬ 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.‬

‭3.‬ ‭Naming Conventions‬‭:‬

‭○‬ O
‭ perations that should be overridden can be prefixed to identify them, such as‬
DoCreateDocument‬‭or‬‭
‭ DoRead‬ ‭, following a consistent‬‭naming strategy.‬
‭Known Uses‬

‭●‬ T
‭ emplate methods‬‭are fundamental and often seen in‬‭m ost abstract classes where‬
‭algorithmic structure is defined.‬

‭Related Patterns‬

‭●‬ F
‭ actory Methods‬‭: Often called by template methods‬‭to instantiate objects required‬
‭for the algorithm.‬

‭●‬ S
‭ trategy‬‭: Template methods use inheritance to vary‬‭part of an algorithm, while‬
‭s trategies delegate the entire algorithm to external objects.‬

‭Visitor Design Pattern‬

‭Intent‬

‭ he‬‭Visitor‬‭pattern 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.‬

‭Applicability of the Visitor Pattern‬

‭Use the‬‭Visitor‬‭pattern when:‬

‭1.‬ ‭O bject structure contains many classes with differing interfaces‬‭:‬

‭○‬ I‭f 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.‬

‭2.‬ ‭Avoiding "polluting" classes with unrelated operations‬‭:‬

‭○‬ 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.‬

‭3.‬ ‭O bject structure is shared across many applications‬‭:‬

‭○‬ I‭f the object structure is shared across different applications, the Visitor pattern‬
‭lets you encapsulate operations in the applications that need them, avoiding‬
‭unnecessary coupling.‬

‭4.‬ ‭O bject structure classes rarely change‬‭:‬

‭○‬ I‭f 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‬

‭1.‬ ‭Visitor Class‬‭:‬

‭○‬ T visit‬‭operation for each‬


‭ here’s an abstract Visitor class that declares a‬‭
‭type of element in the object structure.‬

‭○‬ T
‭ his allows the Visitor to interact directly with the interface of each specific‬
‭element type.‬

‭2.‬ ‭ConcreteVisitor‬‭:‬

‭○‬ T visit‬‭m ethods with logic‬‭s pecific to each‬


‭ hese classes implement the‬‭
‭element type.‬

‭3.‬ ‭Element Classes‬‭:‬

ElementA‬
‭○‬ ‭Each class in the object structure (like‬‭ ElementB‬
‭,‬‭ ‭, etc.)‬
accept‬‭m ethod.‬
‭implements an‬‭

visit‬‭m ethod.‬
‭○‬ ‭This method takes a Visitor and calls the corresponding‬‭
‭○‬ S
‭ o, which method gets executed depends on‬‭both‬‭the‬‭type of the Visitor and‬
‭the type of the Element.‬

‭Key Concepts‬

‭1. Double Dispatch:‬

‭●‬ ‭The Visitor pattern uses‬‭double dispatch‬‭:‬

accept‬‭m ethod in the element takes a visitor.‬


‭○‬ ‭The‬‭

visit‬‭m ethod‬‭on the visitor.‬


‭○‬ ‭The element then calls the appropriate‬‭

‭○‬ T
‭ his lets the program decide behavior based on‬‭two‬‭types‬‭: the element and‬
‭the visitor.‬

‭2. Who Traverses the Structure?‬

‭●‬ T
‭ he structure containing the elements (like a list or tree) must ensure each element is‬
‭visited.‬

‭●‬ ‭This traversal can be:‬

‭○‬ ‭Done by the object structure itself (most common).‬

‭○‬ ‭Managed by the visitor.‬

‭○‬ ‭O r handled by a separate iterator object.‬

You might also like