09 Design Pattern
09 Design Pattern
Key requirement:
Chapter 2: Designing a Same interface for simple and complex elements.
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:
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
_imp = windowSystemFactory-
>CreateWindowImp();
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
✔ 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:
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:
Example 4: Visitor
Same structure:
o One visitor → spell check
o Another → hyphenation
6
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
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:
Instead of:
Intent
new Room()
✔ Now:
Real-Life Idea
Change factory → change maze type
Think:
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
✔ 3. Consistency
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
Steps:
Main Components o
o
Build maze
Add rooms
(Participants) o Add doors
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.
11
Design Pattern, 2015 Samak Wardak
Chapter 3: Creational Patterns
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)
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.
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:
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
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
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
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
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.
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)
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.
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.
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:
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
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)
32
Design Pattern, 2015 Samak Wardak