0% found this document useful (0 votes)
2 views32 pages

09 Design Pattern

Chapter 2 discusses the design of a document editor using various design patterns, including Composite, Strategy, and Abstract Factory patterns, to create a flexible and reusable architecture. Key concepts include treating document elements uniformly, separating structure from behavior, and allowing for multiple UI styles and window systems. The chapter emphasizes the importance of encapsulating object creation and maintaining low coupling for better maintainability and extensibility.

Uploaded by

Samiullah Wardak
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)
2 views32 pages

09 Design Pattern

Chapter 2 discusses the design of a document editor using various design patterns, including Composite, Strategy, and Abstract Factory patterns, to create a flexible and reusable architecture. Key concepts include treating document elements uniformly, separating structure from behavior, and allowing for multiple UI styles and window systems. The chapter emphasizes the importance of encapsulating object creation and maintaining low coupling for better maintainability and extensibility.

Uploaded by

Samiullah Wardak
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

Chapter 2: A case study: Designing of a document editor

Design Pattern, 2015


 All elements (text + graphics) are treated
uniformly.

Key requirement:
Chapter 2: Designing a Same interface for simple and complex elements.

Document Editor 2. Composite Pattern

(Lexi)  Used to represent hierarchical structures.


 Treats individual objects and groups the
same way.
Important Definitions
✔ Example:
 WYSIWYG (What You See Is What
You Get)  A single letter and a whole paragraph are
A system where the document appears on both treated as glyphs.
screen exactly as it will when printed.
 Glyph 3. Formatting (Line Breaking)
An abstract object representing any
element in the document (text, image, line,  Formatting = arranging text into
etc.). lines/columns.
 Recursive Composition  Separated from structure for flexibility.
Building complex structures from simpler
ones (e.g., characters → lines → columns
Solution:
→ pages).
 Compositor
An object that handles formatting (e.g.,  Use a Compositor object to handle
breaking text into lines). formatting.
 Composition
A structure that holds glyphs and uses a 4. Strategy Pattern
compositor to format them.
 Transparent Enclosure  Encapsulates different algorithms.
Wrapping an object (like adding a border)
without changing how it is used. ✔ In Lexi:
 Factory (GUIFactory)
An object that creates UI elements  Different formatting algorithms (fast vs
(buttons, scrollbars) without specifying high-quality) are interchangeable.
exact classes.
 Window & WindowImp 5. UI Embellishment (Borders,
Abstraction layers to support different Scrollbars)
window systems.
 Add features without modifying existing
Key Concepts classes.

Solution:
1. Document Structure (Core Idea)
 Wrap objects using MonoGlyph
 Documents are hierarchical:
(Decorator style).
o Characters → Lines → Columns
→ Pages
 Represented using objects (glyphs). 6. Decorator Pattern

1
Design Pattern, 2015 Samak Wardak
Chapter 2: A case study: Designing of a document editor
 Adds responsibilities dynamically. ✔ Benefit:

✔ Example:  Easy to switch systems without changing


main code.
 Add border or scrollbar without changing
original object.
Main Ideas
7. Supporting Multiple Look-and-Feel
 Use design patterns to solve complex
Styles
software design problems.
 Separate:
 Different UI styles (Motif, PM, etc.)
o Structure vs behavior
o Interface vs implementation
Problem:  Aim for:
o Flexibility
 Hardcoding UI classes = inflexible. o Reusability
o Maintainability
Solution:
Big takeaway:
 Use Abstract Factory Pattern Good design = low coupling + high flexibility

8. Abstract Factory Pattern


Short Examples
 Creates families of related objects.
Example 1: Composite
✔ Example:
 A paragraph contains lines, lines contain
 One factory creates all “Motif-style” words.
widgets.  Treat all as Glyph objects.
 Another creates “PM-style” widgets.

9. Supporting Multiple Window Systems


Example 2: Strategy (Formatting)
 Different OS window systems (X,
Windows, etc.)  SimpleCompositor → fast but basic
formatting
Problem:  TeXCompositor → slower but high-
quality formatting
 Incompatible APIs.

Solution:
Example 3: Decorator
 Use Window abstraction + WindowImp
implementation  Add border:
 Border(Scroller(Composition))
 Easily change order or remove features.
10. Separation of Abstraction &
Implementation

 Window = interface
Example 4: Abstract Factory
 WindowImp = platform-specific
implementation
2
Design Pattern, 2015 Samak Wardak
Chapter 2: A case study: Designing of a document editor
ScrollBar* sb = guiFactory-  WindowSystemFactory (Abstract
>CreateScrollBar();
Factory)
Creates system-dependent objects like
✔ No dependency on specific UI style. WindowImp, ColorImp, etc.
 Bridge Pattern
Separates abstraction (Window) from
implementation (WindowImp).
Example 5: Window System  Command
Encapsulates a user request as an object.
 Same DrawRect() call works on:  Undo/Redo
o X Window system Mechanism to reverse or reapply
o Presentation Manager operations.
 Command History
✔ Implementation hidden in WindowImp List of executed commands for undo/redo.
 Iterator
Object used to traverse elements without
exposing structure.
 Visitor
Final Quick Revision Object that performs operations on
Points elements of a structure.

 Composite → structure
 Strategy → algorithms
 Decorator → add features Key Concepts
 Abstract Factory → UI families
 Bridge (Window/WindowImp) →
1. Configuring Windows (Abstract
platform independence
Factory)
Here’s a clear, simple, exam-focused summary
of your chapter section: Problem:
How does a Window know which WindowImp
(implementation) to use?

Solution:
Configuring
 Use Abstract Factory
Windows, User  Create a factory for each system:
o PMWindowSystemFactory
Operations, Iterator & o XWindowSystemFactory

Visitor Patterns ✔ Example:

_imp = windowSystemFactory-
>CreateWindowImp();

Important Definitions Benefit:

 Platform independence
 WindowImp
 Easy to switch window systems
Platform-specific implementation of a
window (e.g., for X Window, PM).

3
Design Pattern, 2015 Samak Wardak
Chapter 2: A case study: Designing of a document editor
2. Bridge Pattern (Window +  Delete text
WindowImp)  Change font

Idea: ✔ Usage:

menuItem->Execute();
 Separate:
o Window (what user sees)
o WindowImp (how it works
internally) 5. Undo/Redo System

✔ Benefit:  Each command stores its state


 Use:
o Execute() → do
 Change implementation without affecting
o Unexecute() → undo
interface
 Supports multiple platforms
Important:
Simple view:
 Only meaningful actions should be
Window → uses → WindowImp undoable

3. User Operations Problem


6. Command History
Issues:
Keeps track of all commands
 Same operation from different UI (menu,
button) ✔ Behavior:
 Avoid tight coupling
 Support undo/redo  Undo → move left
 Redo → move right
Solution:
Think of it like a timeline:
 Use Command Pattern
[Cmd1] [Cmd2] [Cmd3] ← present

4. Command Pattern Iterator Pattern


Idea: (Traversal)
 Convert requests into objects 7. Problem

✔ Structure:  Data is stored in complex structures (trees


of glyphs)
 Command → base class  Different traversals needed:
o Preorder
 Execute() → perform action
o Inorder
 Unexecute() → undo action
o Reverse

✔ Example:
We don’t want:

4
Design Pattern, 2015 Samak Wardak
Chapter 2: A case study: Designing of a document editor
 To expose internal structure ✔ Key idea:
 To modify classes for every traversal
 Visitor “visits” each object

✔ Methods:
8. Iterator Solution
VisitCharacter()
Use Iterator object VisitRow()
VisitImage()

✔ Main methods:
✔ Glyph uses:
 First()
Accept(visitor);
 Next()
 IsDone()
 CurrentItem()
11. Example
✔ Example:
 SpellingCheckingVisitor
for ([Link](); ![Link](); [Link]()) { o Checks each character
// process element o Builds words
} o Finds mistakes
 HyphenationVisitor
Benefits: o Finds hyphen points
o Inserts special glyphs
 Works with any structure (array, list, tree)
 Multiple traversals at same time
 Easy to extend
Main Ideas
 Separate:
Visitor Pattern (Analysis) o Interface vs implementation →
(Bridge)
9. Problem o Request vs execution →
(Command)
 Need different analyses: o Structure vs traversal → (Iterator)
o Spell check o Structure vs analysis → (Visitor)
o Hyphenation
o Word count Core principle:
“Encapsulate what changes”
But:

 Don’t want to modify Glyph classes every


time
Short Examples
Example 1: Abstract Factory
10. Visitor Solution
 Choose window system:
o X system → XWindowImp
Separate analysis from structure
o PM system → PMWindowImp

5
Design Pattern, 2015 Samak Wardak
Chapter 2: A case study: Designing of a document editor

Example 2: Command

 Menu click:
o Calls Execute()
 Undo:
o Calls Unexecute()

Example 3: Iterator

 Traverse document:

for each glyph → process

Example 4: Visitor

 Same structure:
o One visitor → spell check
o Another → hyphenation

Final Quick Revision Points


 Abstract Factory → create platform
objects
 Bridge → separate interface &
implementation
 Command → encapsulate actions +
undo
 Iterator → traverse structure
 Visitor → add new operations easily

Here’s a simple, exam-ready summary of your


chapter section on Creational Patterns &
Abstract Factory:

6
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns

Chapter 3: Creational 2. Two Main Themes


Patterns 1. Encapsulation of object creation
o System doesn’t know which
concrete classes are used
Important Definitions 2. Abstraction
o System uses only interfaces, not
 Creational Patterns implementations
Design patterns that deal with object
creation in a flexible and reusable way.
✔ Result:
 Class Creational Pattern
Uses inheritance to decide which class to
 Easy to change:
create.
o What is created
 Object Creational Pattern
o How it is created
Uses composition (delegation) to create
o When it is created
objects.
 Instantiation
The process of creating an object from a
class.
 Abstract Factory Pattern 3. Maze Example (Core Example)
Provides an interface to create families of
related objects without specifying their  Maze = collection of rooms
exact classes.  Components:
o Room
 Product Family o Wall
A group of related objects that are o Door
designed to work together.  Base class:
o MapSite → has Enter() method
Key Concepts
Behavior:
1. Why Creational Patterns?
 Enter room → move
 Enter door:
Problem: o Open → pass
o Closed → blocked
 Hardcoding object creation makes code:
o Rigid
o Hard to modify
o Difficult to reuse
4. Problem with Simple Design
Solution: new Room()
new Wall()
 Use creational patterns to: new Door()
o Hide object creation
o Increase flexibility ❌ Issues:

Key idea:  Hardcoded classes


 Not flexible
“Don’t hardcode objects—delegate their  Difficult to extend (e.g., enchanted maze)
creation.”

7
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
4. ConcreteProduct
Creational Pattern o Actual implementation
Solutions 5. Client
o Uses only interfaces

✔ 5 Main Patterns

Pattern Idea
Example (Widgets)
Factory Subclass decides object
Method creation  Abstract:
Abstract o WidgetFactory
Create families of objects
Factory o ScrollBar, Window
Build complex objects step-by-  Concrete:
Builder o MotifFactory
step o PMFactory
Prototype Clone existing objects
Singleton Only one instance exists ✔ Result:

 Switch UI style easily


Abstract Factory Pattern
(Main Focus)
Maze Example with Factory

Instead of:
Intent
new Room()

Create related objects without specifying


Use:
their exact classes.
[Link]()

✔ Now:
Real-Life Idea
 Change factory → change maze type
Think:

 One factory for Windows UI


 Another for Mac UI Types of Mazes
Same code, different look.
 Normal Maze
 Enchanted Maze
o Special rooms, magic doors
 Bombed Maze
Structure o Rooms with bombs, damaged walls

1. AbstractFactory Just change factory:


o Declares creation methods
2. ConcreteFactory [Link](factory);
o Creates specific objects
3. AbstractProduct
o Interface for products
8
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns

Main Ideas Short Examples


 Separate: Example 1: Without Factory
o Object creation from usage
 Avoid: Room* r = new Room();
o Hardcoding classes
 Use: ❌ Not flexible
o Interfaces for flexibility

Big concept:
Example 2: With Factory
“Code to interface, not implementation.”
Room* r = [Link]();

✔ Flexible
Benefits (Advantages)
✔ 1. Isolation of concrete classes Example 3: Switching Families
 Client doesn’t know exact classes MazeFactory f1; // normal
EnchantedMazeFactory f2;
BombedMazeFactory f3;
✔ 2. Easy switching

 Change factory → change entire system ✔ Same code, different behavior

✔ 3. Consistency

 Ensures compatible objects Final Quick Revision Points


 Creational Patterns → object creation
 Abstract Factory → families of objects
 Encapsulation → hide creation logic
Drawbacks  Flexibility → easy to change system
 Maze example → shows pattern use
❌ Hard to add new product types
Here’s a clear, exam-focused summary of the
 Must modify factory interface Builder Pattern:

Implementation Tips BUILDER PATTERN




Factories are often Singletons
Can use:
(Creational)
o Factory Method
o Prototype (cloning) ✅ Definition (Important)
 Builder Pattern separates:

9
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
o How an object is built
(construction process) How It Works (Simple
o from what the object looks like Flow)
(representation)
 This allows the same construction 1. Client chooses a Builder
process to create different versions of an 2. Gives it to the Director
object. 3. Director builds object step-by-step
4. Builder constructs and stores result
5. Client gets final product from Builder

Key Concepts
1. Separation of concerns Main Idea
 Construction logic ≠ Final object  Same process → different results
representation  Focus: how to build, not what to build
 Example: One process → multiple outputs

2. Step-by-step construction

 Object is built gradually, not in one go Example (Simple)


3. Reusability RTF Document Conversion

 Same building process can create:  Director: RTFReader (reads document)


o ASCII text  Builders:
o TeX format o ASCIIConverter → plain text
o GUI text widget o TeXConverter → formatted text
o TextWidgetConverter → editable
4. Flexibility UI

 Add new representations without Same RTF input → different outputs


changing existing code
Maze Example

 Steps:
Main Components o
o
Build maze
Add rooms
(Participants) o Add doors

Component Role Different builders:


Defines steps to build object
Builder  StandardMazeBuilder → real maze
parts
 CountingMazeBuilder → just counts
ConcreteBuilder Implements building steps rooms/doors
Director Controls the building process
Product Final complex object

When to Use (Applicability)


10
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
Use Builder when:  Builds objects step-by-step
 Key benefit: Same process → different
 Object creation is complex products
 You need different representations
 You want to reuse construction process Here’s a simple, exam-ready summary of the
Prototype Pattern:

Key Advantages
(Consequences) PROTOTYPE
1. Change representation easily PATTERN (Creational)
 Just create a new Builder ✅ Definition (Important)
2. Cleaner code (modularity)  The Prototype Pattern creates new
objects by copying (cloning) an existing
 Construction logic is separated object (called a prototype).
 Instead of creating objects from scratch,
3. Better control we duplicate an existing instance.

 Build object step-by-step

Important Notes Key Concepts


 Builder does NOT create objects directly 1. Cloning instead of creating
 It only defines how to build
 ConcreteBuilder does the actual work  Objects are created using a Clone()
method
 Faster and avoids complex construction
Short Analogy (Easy to
Remember) 2. Prototype instance

Think of building a house:  A pre-created object used as a template


 New objects = copies of this prototype
 Director = Engineer (gives instructions)
 Builder = Construction team 3. Object composition over subclassing
 Different builders:
o Build wooden house  Instead of many subclasses → use
o Build concrete house different prototypes

Same plan, different results 4. Runtime flexibility

 You can add/remove prototypes while the


Quick Exam Summary program is running
 Pattern type: Creational
 Purpose: Separate construction from
representation

11
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns

Main Components Tool Example


(Participants)  GraphicTool holds a prototype
 When user clicks:
Component Role o Tool clones prototype
Prototype Declares cloning method o Adds it to document

ConcretePrototype Implements cloning


One tool class → many object types
Uses prototype to create
Client
new objects

When to Use
How It Works (Simple
(Applicability)
Flow)
Use Prototype when:
1. Create a prototype object
2. Store it  Object creation is expensive or complex
3. Client requests a new object  You want to avoid many subclasses
4. Prototype clones itself  Objects are decided at runtime
5. Return the new object  Objects differ only in state (data)

Main Idea Key Advantages


 Copy existing object → get new object (Consequences)
 Avoids creating objects from scratch
1. Add/remove objects at runtime

 Just register new prototypes


Example (Simple)
2. Fewer classes
Music Editor Example  No need for many subclasses
 Objects: notes, staves, etc.
 Instead of creating new notes every time: 3. Flexible object creation
o Store a prototype note
o Clone it when needed  Change behavior by changing prototype

Example: 4. Supports complex objects

 Whole note prototype → clone → new  Can clone structures (like trees, circuits)
whole note
 Half note prototype → clone → new half Disadvantages
note
 Every class must implement Clone()
 Hard if:
o Object has complex structure

12
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
o Circular references exist  Prototype Manager: A registry
(collection) that stores and provides
prototypes using keys.
 Shallow Copy: Copies object, but shares
internal data (references).
Short Analogy (Easy to  Deep Copy: Copies object and duplicates
Remember) all internal data, making it independent.

Think of a photocopy machine :

 Original document = Prototype Key Concepts


 Copies = New objects
 Objects are created using a Clone()
Instead of writing again, just copy method.
 Useful when:
o Creating objects is expensive or
complex.
Quick Exam Summary o You want to avoid many
subclasses.
 Pattern type: Creational  Works best in static languages (like
 Purpose: Create objects by cloning C++).
 Key method: Clone()
 Benefit: Fast, flexible, fewer classes

Main Ideas
One-Line Memory Trick 1. Prototype Manager
o Stores prototypes in a registry.
o Clients request a prototype and
“Don’t create—duplicate.”
clone it.
o Allows dynamic addition/removal
Here’s a clean, exam-ready summary of your
of objects.
chapter section on Prototype & Singleton
2. Clone Operation
patterns + discussion of creational patterns:
o Core of the pattern.
o Must handle:
 Deep vs shallow copy
 Complex structures (e.g.,
1. PROTOTYPE circular references)
3. Initialization After Cloning
PATTERN o Cloned objects may need
customization.
o Use an Initialize() method
Important Definitions instead of passing parameters to
Clone().
 Prototype Pattern: Create new objects by 4. Save/Load Trick
copying (cloning) an existing object o Clone by saving object state and
(prototype) instead of creating from reloading it.
scratch.

13
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
o Object created only inside the
Short Example class.
2. Global Access Point
Door* door = prototypeDoor->Clone();
door->Initialize(room1, room2); o Access through:
o Singleton::Instance();
3. Lazy Initialization
Clone first → then customize. 4. if (_instance == 0)
5. _instance = new Singleton;
6. Subclassing
o Singleton can be extended.
o Instance may return subclass
Important Notes objects.
7. Registry Approach
 Deep copy is usually required for o Store multiple singleton types by
independence. name.
 Clone must be implemented carefully. o More flexible than hardcoding.
 Avoid forcing parameters into Clone →
breaks uniformity.

Short Example
2. SINGLETON Singleton* s = Singleton::Instance();

PATTERN
Important Notes
✅ Important Definitions
 Better than global variables (cleaner
 Singleton Pattern: Ensures a class has design).
only one instance and provides a global  Avoid static global objects due to:
access point to it. o Initialization order problems
o Unused objects being created

Key Concepts
Advantages
 Only one object exists (e.g., printer
manager, file system).  Controlled access
 Controlled access via a static method (e.g.,  No namespace pollution
Instance()).  Flexible (can extend or modify instance
 Uses lazy initialization (created only count)
when needed).

3. DISCUSSION OF
Main Ideas
CREATIONAL
1. Single Instance Control
o Constructor is hidden/protected. PATTERNS
14
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
o Creating many subclasses
Key Concepts  Do:
o Use one prototype and clone it
There are two ways to control object creation:

1. Using Inheritance (Factory Method)

 Subclass decides what to create.


Final Takeaways
 ❌ Problem: Too many subclasses.
 Start simple (Factory Method)
 Move to:
2. Using Composition (Better approach) o Prototype / Abstract Factory /
Builder
 Use objects (factories/prototypes) to create
when flexibility is needed
objects.
 Used in:
o Prototype
o Abstract Factory
o Builder QUICK REVISION (1-
Minute)
Main Ideas  Prototype → Clone objects
 Singleton → Only one instance
 Deep Copy > Shallow Copy (usually)
Pattern Comparison
 Prototype Manager → stores prototypes
 Singleton Instance() → global access
Pattern How it Works Drawback  Composition > Inheritance for flexibility
Factory Subclass Too many
Method creates objects subclasses Here’s a simple, exam-focused summary of your
Abstract Factory object Many factory section on Structural Patterns + Adapter +
Factory creates families classes Bridge:
Clone existing Needs Clone
Prototype
object implementation

Key Insight
 Prototype is often best when:
o You want fewer classes
o You need flexible object creation
o You can reuse cloning (e.g.,
duplicate feature)

Short Example
(Conceptual)
 Instead of:
15
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns
o Facade → Simplify complex
systems
1. STRUCTURAL o Decorator → Add features
dynamically
PATTERNS
(Overview)
Short Example
✅ Important Definitions
 Instead of rewriting a class → wrap it
 Structural Patterns: Deal with how (Adapter)
classes and objects are combined to form  Instead of hardcoding → compose objects
larger, flexible structures. dynamically
 Class Structural Patterns: Use
inheritance (fixed at compile time).
 Object Structural Patterns: Use
composition (flexible at run-time).
2. ADAPTER
PATTERN
Key Concepts
✅ Important Definitions
 Inheritance (Class level) → Static, less
flexible  Adapter Pattern: Converts one interface
 Composition (Object level) → Dynamic, into another that clients expect.
more flexible  Also called: Wrapper
 Focus is on:
o Reusing existing classes
o Making incompatible classes work
together
o Building complex systems from Key Concepts
simple parts
 Used when:
o You have an existing class
o But its interface is incompatible
 Adapter acts as a translator
Main Ideas
 Structural patterns improve:
o Flexibility
o Reusability Main Ideas
o Maintainability
 Examples: 1. Purpose
o Adapter → Fix incompatible o Make incompatible classes work
interfaces together
o Bridge → Separate abstraction 2. Two Types
from implementation o Class Adapter
o Composite → Tree structures  Uses inheritance
o Proxy → Placeholder object  Less flexible
o Flyweight → Share objects o Object Adapter
(memory saving)  Uses composition

16
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns
 More flexible (preferred)
3. Participants
Important Definitions
o Target → expected interface
 Bridge Pattern: Separates abstraction
o Adaptee → existing class
from implementation so both can change
o Adapter → converts interface
independently.
o Client → uses Target interface
4. How it works
o Client → Adapter → Adaptee

Key Concepts
 Avoids explosion of subclasses
Short Example  Uses composition instead of inheritance
 Two separate hierarchies:
Problem: o Abstraction
o Implementation
 App expects Shape
 You have TextView

Solution:
Main Ideas
_text->GetExtent(width, height); //
adaptee call 1. Problem
o Too many subclasses when
Adapter converts it to: combining variations
o Example:
BoundingBox(...)  Window types × Platforms
→ many classes
2. Solution
o Split into:
Class vs Object Adapter  Abstraction (Window)
 Implementor
Class Object (WindowImp)
Feature
Adapter Adapter 3. How it works
Mechanism Inheritance Composition o Abstraction holds reference to
Flexibility Low High implementation
o Delegates work to it
Works with
No Yes
subclasses

Important Notes Short Example


imp->DeviceRect(x1, y1, x2, y2);
 Adapter may also add missing
functionality Window delegates drawing to platform-
 Can be simple (rename methods) or specific implementation.
complex

Structure
3. BRIDGE PATTERN
17
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns
 Abstraction → main interface
 RefinedAbstraction → specialized 1. COMPOSITE
version
 Implementor → interface for Pattern (Structural)
implementation
 ConcreteImplementor → actual
implementation ✅ Important Definitions
 Composite Pattern: A design pattern that
organizes objects into tree structures to
represent part-whole relationships.
Advantages  It allows clients to treat individual
objects (leaf) and groups of objects
 Change implementation without affecting (composite) the same way.
clients
 Extend abstraction and implementation
separately
 Better scalability
Key Concepts
 Tree Structure: Objects are arranged like
a hierarchy (parent → children).
Key Difference from Adapter  Uniformity: No need to distinguish
between single objects and groups.
Adapter Bridge  Recursive Composition: A composite can
Fix existing Design flexibility from contain other composites.
incompatibility start
Works after design Used during design
Changes interface Keeps interface same
Main Components

QUICK REVISION (1- 1. Component (Graphic)


o Common interface for all objects

Minute) o Defines operations like Draw()


2. Leaf (Line, Text, Rectangle)
o Basic objects (no children)
 Structural Patterns → How 3. Composite (Picture)
objects/classes are combined o Contains child components
 Adapter → Convert interface (translator) o Implements operations by calling
 Bridge → Separate abstraction & children
implementation 4. Client
 Composition > Inheritance for flexibility o Uses Component interface (doesn’t
 Object Adapter > Class Adapter care if object is leaf or composite)
(usually)

Here is a clear, exam-ready summary of the


Composite and Decorator design patterns:
Main Ideas
 Simplifies client code → no need to check
object type
 Supports hierarchical structures
18
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns
 Easy to add new types (open for extension)  Decorator Pattern: A design pattern that
 Trade-off: adds new functionality to objects
o ✔ Flexibility dynamically without changing their
o ❌ Hard to restrict allowed child structure.
types  Also called Wrapper.

How It Works Key Concepts


 If object = Leaf → do operation directly  Dynamic behavior addition (at runtime)
 If object = Composite → forward  Composition instead of inheritance
operation to children  Transparent wrapping (client doesn’t
notice decoration)

Short Example
Main Components
Graphics System
1. Component (VisualComponent)
 Leaf: Line, Text o Common interface
 Composite: Picture 2. ConcreteComponent (TextView)
o Original object
Picture 3. Decorator
├── Line o Wraps component
├── Text o Forwards requests
└── Picture
├── Line
4. ConcreteDecorator (Border, Scroll)
└── Text o Adds extra behavior

Calling Draw() on Picture → calls Draw() on all


children.
Main Ideas
 More flexible than inheritance
When to Use  You can combine multiple features
 Avoids creating many subclasses
 When working with tree-like structures  Trade-offs:
 When you want uniform treatment of o ❌ Many small objects
objects o ❌ Harder to debug

How It Works
2. DECORATOR
 Decorator wraps object
Pattern (Structural)  Forwards request
 Adds behavior before/after

✅ Important Definitions
19
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns

Short Example Final Quick Insight


Text Editor UI  Composite = “Treat group like single
object”
 Base: TextView  Decorator = “Add features without
 Add features: changing object”
o Scroll
o Border Here’s a simple, exam-ready summary of the
two patterns: Facade and Flyweight.
TextView

ScrollDecorator

BorderDecorator

Calling Draw():
FACADE Pattern
1. Border draws border
(Object Structural)
2. Scroll handles scrolling
3. TextView displays text ✅ Important Definition
 Facade Pattern: Provides a simple,
unified interface to a complex subsystem,
When to Use making it easier to use.

 Add features without modifying class


 Need runtime flexibility
 Avoid subclass explosion Key Concepts
 Hides complexity behind a single entry
point.
 Does not remove subsystem classes →
Composite vs 
just simplifies access.
Promotes low coupling (clients don’t
Decorator (Quick 
depend on many classes).
Works like a wrapper or front desk.
Difference)
Feature Composite Decorator
Build tree Add behavior
Main Ideas
Purpose
structures dynamically
 Complex systems have many classes →
Part-whole Extending hard for clients to use.
Focus
hierarchy functionality  A Facade class:
Tree (parent- o Knows which subsystem class to
Structure Wrapper layers
children) call.
Client Same for all Same interface o Delegates requests to them.
View objects maintained  Clients interact only with the facade, not
all classes.

20
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns
 Subsystem classes: Scanner, Parser,
CodeGenerator
 Facade: Compiler
Structure (Simple View)
Without Facade:
 Facade → main interface (e.g., Compiler) Client → Scanner → Parser → Builder →
Generator
 Subsystem classes → do real work (e.g.,
Scanner, Parser) With Facade:
 Client → uses Facade Client → Compiler → (handles everything)

How It Works FLYWEIGHT


1. Client calls Facade.
Pattern (Object
2. Facade forwards request to subsystem
classes.
Structural)
3. Subsystem does the work.
4. Result returned to client. ✅ Important Definition
 Flyweight Pattern: Reduces memory
usage by sharing objects instead of
When to Use creating many similar ones.

 When system is complex and hard to use.


 When you want to reduce dependencies.
 When organizing system into layers. Key Concepts
 Sharing objects across multiple contexts.
 Splits state into:
Advantages o Intrinsic state (shared, stored
inside object)
o Extrinsic state (external, passed
 Easy to use (simple interface)
by client)
 Reduces coupling
 Improves maintainability
 Clients don’t need to know internals

Main Ideas
Disadvantages  Many small objects → high memory cost.
 Solution:
o Create one shared object.
 Adds an extra layer
o Reuse it in different places.
 May limit access to full functionality (but
 Clients provide context when needed.
can bypass if needed)

Short Example
Compiler system:
Structure (Simple View)
21
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns
 Flyweight → interface External (per use):
Position = (x, y)
 ConcreteFlyweight → shared object
Font = Arial, 12
 FlyweightFactory → manages shared
objects
 Client → provides extrinsic state
Quick Comparison
How It Works
Feature Facade Flyweight
1. Client requests object from factory. Purpose Simplify interface Save memory
2. Factory:
Focus Ease of use Efficiency
o Returns existing object OR
o Creates new one if needed. Key Idea One entry point Object sharing
3. Client passes external data when using it. Used When System is complex Too many objects

When to Use
Easy Way to Remember
 Large number of similar objects
 Memory usage is high  Facade = “Front door” → makes things
 Objects share common data easier
 Flyweight = “Sharing” → saves memory
Advantages Here’s a concise, exam-ready summary of the
Proxy Pattern section:
 Saves memory
 Improves performance for large systems
 Enables fine-grained objects Important Definitions
 Proxy Pattern: A structural design pattern
Disadvantages that provides a surrogate or placeholder for
another object to control access to it.
 More complex design  Also Known As: Surrogate.
 Extra cost of managing external (extrinsic)  Participants:
state o Proxy (e.g., ImageProxy):
Controls access to the real object;
forwards requests; may create the
Short Example real object on demand.
o Subject (e.g., Graphic): Defines
Text editor with characters: the interface that both RealSubject
and Proxy implement.
Without Flyweight: o RealSubject (e.g., Image): The
actual object that the proxy
 100,000 characters → 100,000 objects ❌ represents.

With Flyweight: Key Concepts


 Only ~128 character objects (ASCII) ✅ 1. Intent: Allow controlled access to an
 Position & style stored externally object, often to defer expensive creation,
enforce access control, or provide
Shared:
Character 'A' additional services.

22
Design Pattern, 2015 Samak Wardak
Chapter 4: Structural Patterns
2. Motivation Example: In a document  Smalltalk Technique: Use
editor, large images are expensive to load. doesNotUnderstand: to forward
A proxy can act as a stand-in and only messages to the real object.
create the image when it is visible (on-  Optimization: Copy-on-write—proxy
demand). increments reference count and only
3. Types of Proxies: copies object if modified.
o Virtual Proxy: Creates expensive
objects on demand (e.g., Example Usage:
ImageProxy).
o Remote Proxy: Represents objects TextDocument* text = new TextDocument();
in different address spaces. text->Insert(new
ImageProxy("[Link]"));
o Protection Proxy: Controls access image->Draw(Point(50, 100)); // Image
based on permissions. loaded on-demand
o Smart Reference: Adds extra
housekeeping, like reference
counting or lazy loading. Key Differences from Related
4. Consequences: Patterns
o Introduces indirection.
o Supports optimizations like on-
Pattern Purpose
demand creation or copy-on-write.
o Can hide object location, expensive
Adds responsibilities to an object
Decorator dynamically; supports recursive
operations, or access control logic
from clients. composition.
Controls access to a subject; may
Proxy delay creation, enforce permissions,
Structure & Collaboration or manage references.

 Proxy:
 Proxy focuses on substituting access to a
o Maintains reference to
single object.
RealSubject.
 Decorator focuses on extending
o Implements the same interface as
functionality and can be recursive.
Subject.
o Controls object creation and
access. Short Example
 RealSubject:
o Performs the actual work.  Imagine a photo editor:
 Subject Interface: o ImageProxy holds file name &
o Ensures the proxy can replace the size.
real object transparently. o When the user scrolls to an image,
 Collaboration: Proxy forwards requests to Draw() triggers loading the actual
RealSubject when necessary. image.
o Until then, editor sees a lightweight
Implementation Notes placeholder, improving
performance.
 Virtual Proxy Example:
o Stores file name, bounding box,
and reference to real Image.
o Loads the Image only when
Draw() is called.
 C++ Technique: Overload operator-> to
lazily load objects.

23
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
 Encapsulation of behavior: Patterns like
Chapter 5 Command, Strategy, and State wrap
behavior in objects.
 Flexibility & Extensibility: Patterns allow
Important Definitions adding/changing behavior dynamically
without affecting other objects.
1. Behavioral Patterns – Design patterns  Communication via chains or
that deal with algorithms, responsibilities, mediators: Objects interact indirectly to
and communication between objects rather avoid tight coupling.
than their structure. They simplify
complex control flows by focusing on
object interactions. Main Ideas with Examples
2. Behavioral Class Patterns – Use
inheritance to distribute behavior between Chain of Responsibility
classes.
o Template Method – Abstract  Intent: Avoid coupling sender and
algorithm defined step-by-step; receiver; requests pass along a chain until
subclasses implement abstract handled.
operations.  Example: A help system in a GUI; a
o Interpreter – Represents a button request passes through Button →
grammar as a class hierarchy; Dialog → Application until handled.
interprets statements via class  Structure:
instances. o Handler – interface for request
3. Behavioral Object Patterns – Use object handling; knows successor.
composition to manage responsibilities o ConcreteHandler – handles
and communication. request or forwards it.
o Mediator – Introduces an object to o Client – initiates request.
manage interactions between peers,  Benefits: Reduced coupling, flexible
reducing coupling. responsibility assignment.
o Chain of Responsibility – Passes  Limitation: No guarantee a request is
requests along a chain of objects; handled.
any can handle it.
o Observer – Maintains a Command
dependency; observers are notified
of state changes.  Intent: Encapsulate a request as an object.
o Strategy – Encapsulates  Example: Menu item actions like
algorithms for flexible swapping at PasteCommand or OpenCommand in a text
runtime. editor; supports undo/redo.
o Command – Encapsulates requests  Structure:
as objects for parameterization, o Command – abstract interface.
queuing, undo, or macros. o ConcreteCommand – binds receiver
o State – Encapsulates object states;
and action.
behavior changes as state changes. o Invoker – calls Execute.
o Visitor – Encapsulates operations
o Receiver – performs the actual
applied across classes. operation.
o Iterator – Abstracts traversal over
o Client – creates commands and
object aggregates.
assigns receivers.
 MacroCommand: Executes a sequence of
Key Concepts commands; supports composition.
 Benefits: Decouples invoker from
 Decoupling: Many behavioral patterns executor, supports undo, dynamic
reduce direct knowledge between objects.
24
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
command replacement, and command 6. repetition ::= expression '*'
7. literal ::= 'a' | 'b' | 'c' | ...
logging.
8. Abstract Syntax Tree (AST):
A tree structure representing sentences in
Implementation Notes
the language, composed of classes
corresponding to grammar rules.
 Chain of Responsibility: Can use explicit
9. Context:
links or existing object references; requests
Holds global information used during
can be represented as objects for
interpretation (e.g., the string being parsed
flexibility.
or variable values).
 Command: Commands can be simple (no
arguments/undo) or complex (store
receiver, arguments, state for undo). Key Concepts
Template classes can simplify
implementation for simple commands.  Each grammar rule is represented by a
class.
Short Example for Chain of  Terminal symbols (literals) and
nonterminal symbols (composite
Responsibility expressions) are treated differently:
o TerminalExpression: Handles
Button* button = new Button(dialog, literal values.
PAPER_TOPIC);
o NonterminalExpression: Handles
button->HandleHelp(); // request may be
handled by Button, Dialog, or sequences, alternations, or
Application repetitions and typically calls
Interpret recursively on
subexpressions.
Short Example for Command  The Interpret operation is defined in
each class and processes its part of the
Document* doc = new Document();
Command* paste = new PasteCommand(doc); input using the context.
paste->Execute(); // performs paste
operation without invoker knowing the
details Main Ideas
Here’s a clear, exam-ready summary of the 1. Motivation:
Interpreter Pattern section you provided: When a problem is common (e.g., string
matching with patterns), you can define a
language and an interpreter to solve
Important Definitions instances of the problem rather than
writing a new algorithm for each case.
1. Interpreter Pattern: 2. Applicability:
A behavioral design pattern that defines a o Useful for simple grammars and
grammar for a simple language, represents languages.
sentences in that language, and provides an o Less suitable for complex
interpreter to process them. grammars (parser generators are
2. Grammar: better).
A set of rules that defines valid sentences o Efficiency may be lower than
in a language. Example for regular optimized solutions but the pattern
expressions: is highly extensible.
3. expression ::= literal |
alternation | sequence |
3. Structure:
repetition | '(' expression ')' o AbstractExpression: Base class
4. alternation ::= expression '|' with the Interpret method.
expression o TerminalExpression: Represents
5. sequence ::= expression '&' literal symbols.
expression
25
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
o NonterminalExpression: Summary Tip:
Represents composite rules; holds Think of the Interpreter pattern as a way to treat a
subexpressions. class hierarchy as a mini-language. AST nodes
o Context: Shared information for represent grammar rules, and the Interpret
interpretation. method processes them recursively using a
o Client: Builds the AST and context. Ideal for repeated problems with simple
invokes Interpret. grammars, like regex or Boolean expressions.
4. Benefits and Limitations:
o Easy to extend or modify the Here’s a concise, exam-ready summary of the
grammar. Iterator Pattern chapter section you provided:
o Simple implementation for
grammar rules.
o Hard to maintain for complex
Important Definitions
grammars.
o Supports adding new ways to
1. Iterator Pattern: A behavioral design
interpret expressions (e.g., type- pattern that provides a way to access the
checking, printing). elements of an aggregate object
5. Implementation Notes: sequentially without exposing its
o AST creation is separate from
underlying representation.
interpretation; the pattern doesn’t 2. Aggregate: A collection or container
handle parsing. object (like a List or SkipList) whose
elements can be traversed.
o Can use the Visitor pattern to
implement Interpret separately. 3. Iterator: An object responsible for
o Flyweight pattern can optimize
traversing the aggregate, keeping track of
shared terminals. the current element.
4. External Iterator: Client controls
traversal, explicitly calling Next and
Short Examples CurrentItem.
5. Internal Iterator: Iterator controls
1. Regular Expression Interpreter traversal and applies an operation to each
(Smalltalk): element.
o Classes: LiteralExpression, 6. Polymorphic Iterator: An iterator that
SequenceExpression, works with different aggregate subclasses
AlternationExpression, through a common interface.
RepetitionExpression. 7. Null Iterator: A degenerate iterator that
o Example: Expression raining & represents an empty traversal.
(dogs | cats)* is represented as
an AST.
o Each node’s Interpret checks its
Key Concepts
part of the input string.  Separation of concerns: The traversal
2. Boolean Expression Interpreter (C++): logic is separated from the aggregate
o Grammar includes VariableExp,
object.
Constant, AndExp, OrExp, NotExp.
 Multiple traversals: Different iterators
o Example: (true AND X) OR (Y
can traverse the same collection
AND NOT X)
independently.
o Evaluate interprets the expression
 Traversal policies: Iterators can
based on a Context mapping
implement different strategies (e.g., front-
variables to Boolean values.
to-back, back-to-front, filtered traversal).
o Replace shows the pattern’s
 Factory method integration: Aggregates
flexibility: you can replace
create their own iterators via methods like
variables with other expressions
CreateIterator to support polymorphic
and reinterpret.
iteration.
26
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
 Robustness: Iterators must handle changes Internal Iterator (process first 10 elements):
to the aggregate during traversal, often
using internal tracking or registration class PrintNEmployees : public
ListTraverser<Employee*> {
mechanisms.
protected:
bool ProcessItem(Employee* const& e)
Main Ideas override {
_count++;
e->Print();
1. Motivation: Accessing a collection should return _count < _total;
not expose its internal structure. Iterators }
handle traversal while keeping the };
PrintNEmployees pa(employees, 10);
aggregate encapsulated. [Link]();
2. Structure:
o Iterator Interface: Defines Polymorphic Iterator (independent of concrete
First(), Next(), IsDone(), and
List):
CurrentItem().
o Concrete Iterator: Implements the AbstractList<Employee*>* employees;
traversal logic for a specific Iterator<Employee*>* iterator =
aggregate. employees->CreateIterator();
PrintEmployees(*iterator);
o Aggregate Interface: Defines
delete iterator;
CreateIterator().
o Concrete Aggregate: Returns a
Filtering Iterator (process items matching a
specific iterator instance. condition):
3. External vs Internal Iterators:
o External: Flexible, client-driven, FilteringListTraverser<Employee*>
easy to compare collections. filter(employees);
o Internal: Encapsulates traversal, [Link](); // only processes
reusable, requires subclassing or employees passing TestItem()
function pointers.
4. Polymorphism: Abstract aggregate and Summary Insight:
iterator interfaces allow iteration over The Iterator pattern standardizes traversal for all
multiple collection types without changing kinds of collections, decouples traversal from
client code. collection implementation, and allows multiple,
5. Safety & Cleanup: Use proxies (e.g., flexible, and safe ways to iterate. Internal iterators
IteratorPtr) or smart pointers to ensure simplify client code, while external iterators
dynamically allocated iterators are provide maximum control and flexibility.
properly deleted.
6. Iterators for complex structures: Here’s a concise, exam-ready summary of the
Recursive structures like composites may Mediator, Memento, and Observer behavioral
need path tracking or internal iterators for patterns from your chapter, with key definitions,
traversal. concepts, and examples simplified for easy
7. Enhancements: Filtering iterators, skip-to understanding:
operations, reverse traversal, and null
iterators improve flexibility.

Short Examples 1. Mediator Pattern


External Iterator (front-to-back traversal): Definition / Intent:
Encapsulates how a set of objects interact by
ListIterator<Employee*> i(employees); introducing a mediator object, which promotes
for ([Link](); ![Link](); [Link]()) { loose coupling by letting objects communicate
[Link]()->Print();
}
27
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
indirectly rather than referencing each other 2. Memento Pattern
directly.
Definition / Intent:
Motivation:
Capture and externalize an object’s internal state
so it can be restored later without violating
 Without a mediator, objects can end up
encapsulation.
tightly connected, making the system
fragile and hard to maintain.
Motivation:
 Example: In a dialog box, a button’s state
might depend on an entry field, and the list
 Needed for undo, rollback, or checkpoints
box may affect the entry field. Without
in applications.
mediation, you’d need many subclasses to
 Example: In a graphical editor, moving
handle interactions.
objects connected by a line requires
storing the internal state of the
Key Concepts:
ConstraintSolver to undo moves properly.
 Mediator: Manages and coordinates
Key Concepts:
interactions among objects.
 Colleagues: Objects that communicate
 Originator: The object whose state is
through the mediator instead of directly.
saved/restored (e.g., ConstraintSolver).
 Memento: Stores a snapshot of the
Example:
originator’s state (opaque to others).
 Caretaker: Manages mementos but
 FontDialogDirector acts as a mediator
cannot access or modify them.
between widgets (ListBox, EntryField,
Button) in a font dialog box.
Example:
 Workflow:
1. ListBox selection changes →
 MoveCommand stores a Memento of
notifies mediator.
ConstraintSolver before moving a graphic.
2. Mediator updates EntryField.
 Undo operation restores the previous state
3. Mediator enables or disables
via the Memento.
Buttons accordingly.
Applicability:
Applicability:
Use when:
Use when:
 A snapshot of an object’s state is required
 Complex object interactions exist.
for later restoration.
 Tight coupling reduces reusability.
 Direct access to state would break
 Behavior distributed across objects should
encapsulation.
be customizable without heavy
subclassing.
Consequences / Benefits:
Consequences / Benefits:
1. Preserves encapsulation.
2. Simplifies Originator’s management.
1. Limits subclassing.
3. Can be memory-intensive if states are
2. Decouples objects.
large.
3. Simplifies object protocols.
4. Caretaker must manage storage of
4. Centralizes interaction control (may
mementos.
become complex itself).

3. Observer Pattern
28
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
Definition / Intent:  Pull model: Subject sends minimal
Defines a one-to-many dependency so that when notification; observer queries for details.
one object (Subject) changes state, all its  Trade-offs: Push = less reusable observers;
dependents (Observers) are automatically notified Pull = may be less efficient.
and updated.
Quick Comparison Table
Motivation:
Main
 Supports decoupled designs where Pattern Purpose Example
Players
multiple objects depend on a shared state.
Centralize Mediator, FontDialogDirect
 Example: A spreadsheet and a bar chart Mediato
interaction Colleague or coordinating
both depend on the same data object; r
s s buttons, entry, list
changing the spreadsheet automatically
updates the chart. Originato
Save & ConstraintSolver
Mement r,
restore undo/redo in
Key Concepts: o Memento,
state graphical editor
Caretaker
 Subject: Maintains a list of observers, Auto-
Spreadsheet
provides attach/detach interface. Observe update Subject,
updates bar chart
 Observer: Updates itself when the subject r dependent Observer
on data change
changes. s
 ConcreteSubject / ConcreteObserver:
Implement actual state storage and update Here’s a concise, exam-ready summary of the
behavior. provided text covering Observer, State, and
Strategy patterns from behavioral design
Example: patterns:

 Changing a spreadsheet cell triggers


updates to all subscribed chart objects
Observer Pattern
automatically.
Important Definitions:
Applicability:
Use when:  Observer: An object that wants to be
informed of changes in another object.
 One object’s change affects many others.  Subject: The object being observed.
 You want minimal coupling between  ChangeManager: A mediator object that
objects. manages complex observer-subject
 Observers can be added or removed relationships.
dynamically.
Key Concepts:
Consequences / Benefits:
 Observers can register interest in specific
1. Abstract coupling between Subject and events/aspects.
Observer.  ChangeManager optimizes updates to
2. Supports broadcast communication. avoid redundant notifications.
3. Observers may get unexpected updates;  Combines Subject and Observer interfaces
need careful handling. in languages without multiple inheritance
(e.g., Smalltalk).
Implementation Notes:
Main Ideas:
 Push model: Subject sends detailed
updates.
29
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
 Observers are notified only about the  Table-driven state machines are an
events they care about. alternative but focus on transitions, not
 ChangeManager maps subjects to behavior.
observers, defines update strategies, and
updates observers efficiently. Short Example:
 Concrete example: ClockTimer notifies
DigitalClock and AnalogClock every TCPConnection* conn = new
TCPConnection();
second.
conn->ActiveOpen(); // Delegates to
TCPClosed::ActiveOpen
Short Example: conn->Close(); // Delegates to
TCPEstablished::Close
ClockTimer* timer = new ClockTimer;
AnalogClock* analog = new Known Uses: TCP connection management,
AnalogClock(timer);
DigitalClock* digital = new drawing tools in HotDraw and Unidraw,
DigitalClock(timer); envelope-letter idiom.
// Both clocks update automatically when
timer ticks Related Patterns: Flyweight, Singleton.

Known Uses: Smalltalk MVC, Andrew Toolkit,


Unidraw, Interviews. Strategy Pattern
Related Patterns: Mediator, Singleton. Important Definitions:

 Strategy: An encapsulated algorithm or


State Pattern behavior.
 ConcreteStrategy: A specific
Important Definitions: implementation of a strategy.
 Context: Uses a strategy object to perform
 State: An object representing a particular an operation.
state of a context.
 Context: Maintains the current state and Key Concepts:
delegates requests to it.
 ConcreteState: Implements behavior  Allows algorithm to vary independently
specific to a state. from the context.
 Eliminates conditional statements for
Key Concepts: behavior selection.
 Strategies can be optional or configured at
 Object behavior changes depending on its compile-time (templates in C++).
internal state.
 Encapsulates state-specific behavior in Main Ideas:
separate classes.
 Avoids monolithic conditional statements.  Strategy simplifies maintenance by
 State objects can be shared (flyweight) separating algorithm from context.
and often use Singleton.  Useful when multiple algorithms exist for
a task or behavior.
Main Ideas:  Can share strategies to reduce overhead
(flyweight).
 Transitions between states are explicit and  Provides flexibility for clients to choose
atomic. the algorithm.
 Decentralized transition logic allows easier
modification. Short Example:

30
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
Composition* text = new Composition(new Short Example
TeXCompositor);
text->Repair(); // Line breaks
determined by chosen strategy C++ Example: Document opening in an
application framework.
Known Uses: ET++ line-breaking, RTL compiler
void Application::OpenDocument(const
optimization, financial calculation engines, GUI
char* name) {
input validation. if (!CanOpenDocument(name)) return;
Document* doc = DoCreateDocument();
Related Patterns: Flyweight (for sharing if (doc) {
strategies). _docs->AddDocument(doc);
AboutToOpenDocument(doc);
doc->Open();
Here’s a clear, exam-ready summary of the doc->DoRead();
provided chapter sections on Template Method }
and Visitor behavioral patterns, along with key }
discussion points:
 OpenDocument = template method (fixed
sequence)
Template Method Pattern  CanOpenDocument & DoCreateDocument
= steps defined by subclasses
Important Definitions  AboutToOpenDocument = hook

 Template Method: Defines the skeleton


of an algorithm in a parent class, allowing Visitor Pattern
subclasses to redefine certain steps without
changing the overall algorithm structure. Important Definitions
 Hook Operation: An optional method in
the parent class that a subclass may  Visitor: Represents an operation to be
override. performed on elements of an object
 Primitive Operation: An abstract method structure, allowing new operations without
in the parent class that must be overridden changing element classes.
by a subclass.  Double Dispatch: Ensures operation
selection depends on both the visitor type
Key Concepts and the element type.

 Parent class controls the invariant Key Concepts


(unchanging) part of the algorithm.
 Subclasses provide specific behavior for  Separates operations from object
the varying steps. structures, keeping elements simple.
 Leads to inverted control or "Hollywood  Useful for systems with many unrelated
Principle": “Don’t call us, we’ll call you.” operations on objects.
 Object structures rarely change, but new
Main Ideas operations are frequently added.
 Visitors can maintain state during
 Avoid code duplication by factoring out traversal.
common behavior.
 Subclasses override primitive operations to Main Ideas
customize the algorithm.
 Hooks allow flexible extension without  Two class hierarchies:
breaking the parent algorithm. 1. Elements (e.g., Node classes)
 Useful in frameworks where the sequence 2. Visitors (operations on those
of operations is fixed but behavior varies. elements)

31
Design Pattern, 2015 Samak Wardak
Chapter 5: Behavioral Patterns
 Elements implement Accept(Visitor&) oMediator: Centralized
to delegate operations to visitors. communication.
 Supports accumulation of results (like o Chain of Responsibility: Request
totals or inventory). passed along chain until handled.
 Avoids mixing unrelated operations in  Patterns often work together. E.g.,
element classes. Template Method + Chain of
Responsibility + Visitor + Composite can
Short Example coexist naturally in a system.

C++ Example: Equipment cost computation using Quick Comparison: Template Method vs
a Visitor. Visitor
class EquipmentVisitor {
Template
public: Aspect Visitor
virtual void Method
VisitFloppyDisk(FloppyDisk*); Separate
virtual void VisitChassis(Chassis*); Fixed algorithm
Purpose operations from
}; skeleton
data
class PricingVisitor : public Add new
EquipmentVisitor { Subclasses
Flexibility operations via
private: Currency _total; override steps
public: Visitors
void VisitFloppyDisk(FloppyDisk* e) Parent controls Elements delegate
{ _total += e->NetPrice(); } Control
the sequence to Visitors
void VisitChassis(Chassis* e) {
_total += e->DiscountPrice(); } OpenDocument, PricingVisitor,
Example
}; Display InventoryVisitor
FloppyDisk* disk;
PricingVisitor visitor;
disk->Accept(visitor); // Calls
[Link](disk)

 Accept enables double-dispatch.


 Adding new operations → create a new
Visitor subclass.
 Adding new element types → requires
updating all visitors (drawback).

Behavioral Patterns Discussion


Highlights
 Encapsulating Variation: Many patterns
(Strategy, State, Mediator, Iterator)
encapsulate changing behavior.
 Decoupling: Patterns like Command,
Observer, Mediator, Chain of
Responsibility decouple senders and
receivers differently:
o Command: One-to-one
decoupling.
o Observer: One-to-many
decoupling.

32
Design Pattern, 2015 Samak Wardak

You might also like