DESIGN PATTERNS — COMPLETE TT1 NOTES
DJ Sanghvi COE | [Link] IT Semester VIII | DJ19ITC802
MODULE 1: CREATIONAL PATTERNS MODULE 2: STRUCTURAL PATTERNS
Singleton | Factory Method | Abstract Factory | Adapter | Flyweight | Proxy | Decorator | Facade
Builder | Prototype | Composite
Marks Duration Date Exam
25 Marks 1 Hour 05-03-2024 TT1
EXAM ALERT: TT1 Pattern: Q1 (10 marks) = Singleton OR Builder; Q2 (10 marks) = Design Patterns
+ 3 factors OR Flyweight; Q3 (5 marks) = Match application to pattern
UNIT 1: DESIGN PATTERNS — INTRODUCTION
Definition
A design pattern is a standard solution to a common software problem in a context. It describes a
recurring software structure or idiom, is abstract from any programming language, and identifies classes
and their roles in the solution to a problem.
In 1990, the Gang of Four (GoF) — Gamma, Helm, Johnson, Vlissides — compiled a catalog of design
patterns. Their 1995 book 'Design Patterns: Elements of Reusable Object-Oriented Software' is a
classic of the field.
Benefits of Using Patterns
• Give a design common vocabulary — allows engineers to abstract a problem and talk about it in
isolation from its implementation; domain-specific patterns increase design speed
• Capture expertise and allow it to be communicated — promotes design reuse and avoids
mistakes
• Makes it easier for other developers to understand a system
• Improve documentation and understandability (patterns are described well, once)
3 Factors for Selecting a Design Pattern (QB Q2a — 10 marks)
Factor Explanation Example
Understand the specific problem
Need to manage object creation
you're facing and whether the
1. Problem flexibly? Factory Method or
chosen pattern effectively addresses
Relevance Abstract Factory would be
it. Match the pattern to the problem
suitable.
for a more efficient solution.
Evaluate how well the design pattern Singleton or Observer can aid in
supports scalability and managing global state or handling
2. Scalability &
maintainability. A good pattern communication between
Maintainability
should facilitate easy adaptation to components, enhancing
changing requirements. scalability.
Consider the performance
Flyweight optimizes memory
implications. Some patterns may
3. Performance usage by sharing common state;
introduce overhead or complexity
Considerations Proxy may introduce additional
that could impact system
latency due to indirection.
performance.
GoF Pattern Categories
Creational (Object Structural (Object
Behavioral (Communication)
Instantiation) Combination)
Command, Iterator, Mediator,
Factory Method, Abstract Adapter, Bridge, Composite,
Observer, State, Strategy,
Factory, Singleton, Builder, Decorator, Facade, Flyweight,
Chain of Responsibility,
Prototype Proxy
Template Method, Visitor
SINGLETON PATTERN
Intent: The Singleton design pattern ensures that a class has only one instance and provides a global point
of access to that instance. Used when there should be precisely one instance, such as managing global
configurations, database connections, or resource pools.
Problem it Solves
• Sometimes we really only ever need one instance: login, keyboard reader, printing, game UI,
account manager
• Creating lots of objects can take time and memory
• Multiple objects of a type intended to be unique can lead to bugs
Implementation (3 Steps)
St
Action Reason
ep
Make constructor(s) Cannot be called from outside by clients — prevents external
1
private instantiation
Declare a private static One class-level variable holds the single object; exists
2
instance independent of any instance
Write a public Controls access; creates instance only if it doesn't exist. May
3
getInstance() method need synchronization for multithreaded use.
Code (Python)
class Singleton: __instance = None def __init__(self): if
Singleton.__instance is not None: raise Exception('Cannot instantiate more than
once.') else: Singleton.__instance = self @staticmethod def
get_instance(): if Singleton.__instance is None: Singleton()
return Singleton.__instance # Usage: s1 = Singleton.get_instance() s2 =
Singleton.get_instance() print(s1 is s2) # Output: True
Advantages & Disadvantages
Advantages (Benefits) Disadvantages (Issues)
• Creating lots of objects can take time • Extra
• Takes responsibility of managing that instance
objects take up memory • Difficult in
away from programmer (illegal to construct
multithreaded environments (needs
more instances) • Saves memory • Avoids bugs
synchronization) • Multiple objects of type
arising from multiple instances • Easy global
intended to be unique can lead to bugs • Harder
access point
to unit test (global state)
EXAM ALERT: TT1 Q1(b): 'Discuss the Singleton design pattern. Explain its intent and
implementation along with its advantages and disadvantages.' — 10 marks. HIGHEST
PROBABILITY question.
MEMORY NUMERICAL: Without Singleton: 8 modules × 5 MB = 40 MB | With Singleton: 1 × 5 MB = 5 MB
| Memory Saved = 35 MB
FACTORY METHOD PATTERN
Intent: Defines an interface for creating objects, but lets subclasses decide which class to instantiate. The
type of object created is decided by a separate factory class. Basic Rule: Always program to an Interface.
Problem it Solves
• Client code needs to create objects but should NOT be tightly coupled to specific classes
• Subclasses determine the class of objects to be created
• Class cannot anticipate the types of objects it needs to create
Key Participants (Structure)
Participant Role
Defines the factory method; base class that uses factoryMethod() to
Creator
create product objects
Overrides factory method to instantiate specific ConcreteProduct
ConcreteCreator
classes
Interface for the objects the factory method creates (what all products
Product
share)
ConcreteProduct Implements the Product interface — the actual objects that get created
Real Example: E-commerce supports Credit Card, UPI, Net Banking payments. Client should NOT directly
create objects — system decides at runtime based on user selection → Factory Pattern
Factory Memory/Time Numericals
Factory — Memory Numerical Factory — Time Numerical
10,000 transactions × 3 modules × 12 ms =
4 modules × (500 UG + 500 PG) = 4000
360,000 ms = 6 min After Factory: 10,000 × 7
reports/day × 2 KB = 8 MB After Factory: 1000
ms = 70,000 ms = 1.17 min Saved: 290
reports × 2 KB = 2 MB Saved: 6 MB
seconds ≈ 4.8 minutes
ABSTRACT FACTORY PATTERN
Intent: Provides an interface for creating families of related or dependent objects without specifying their
concrete classes. Creates objects from a family of related products, ensuring compatibility between them.
Factory Method vs Abstract Factory vs Builder — Full Comparison (QB — 10 marks)
Aspect Builder Factory Method Abstract Factory
Create FAMILIES of
Construct complex Define interface for
related/dependent
objects step by step; creating objects;
Purpose objects without
flexible creation with subclasses alter type
specifying concrete
different configurations created
classes
Object creation Creation delegated to
Incremental — each
delegated to concrete factories,
Construction step builds upon
subclasses providing each responsible for a
Process previous to construct
specific family of related
final object
implementations products
Handles complex Used for families of
object construction by Generally simpler — objects which may
Complexity
breaking into smaller creation logic within a involve complex
Handling
steps, multiple method single method interactions between
calls multiple product types
Fine-grained control Flexibility in creating
Flexibility in choosing
over configuration; families of related
Configuration type of object, but
allows optional objects; less fine-
Flexibility limited to single type
parameters and grained control over
per subclass
variations individual object config
EXAM ALERT: TT1 Q1(a): 'Explain Builder design pattern's purpose and how it differs from Factory
Method and Abstract Factory patterns.' — 10 marks
PROTOTYPE PATTERN
Motivation: Prototype Pattern gives us a way to create new objects from the existing instance. It clones the
existing object with its data into a new object. If we do any changes to the cloned object (new object), it
does NOT affect the original object.
When to Use Prototype? (If these appear in problem → Prototype)
• Object creation is costly or time-consuming
• Many similar objects are needed
• You want to avoid complex constructors
Key Participants
Role Responsibility
Requests the Prototype to clone itself, creating a new object via p =
Client
prototype->Clone()
Implements the cloning interface; defines the Clone() method for
Prototype (interface)
creating a copy of itself
Implements Prototype; Clone() method returns a copy of self — each
ConcretePrototype
ConcretePrototype provides its specific implementation
Shallow Copy vs Deep Copy
Aspect Shallow Copy Deep Copy
What gets Object fields copied; nested objects Everything copied including all nested
copied SHARED (same reference) objects (separate references)
Hostel room — you & friend share the
Warden gives SEPARATE key to each.
Analogy SAME physical key. Friend locks room
You lock room → friend is unaffected
→ you're locked out too
MemberwiseClone() — creates shallow Manual deep copy; recursively copy all
C# Method
copy nested objects
Affect Changes to nested objects in clone Changes to clone do NOT affect
Original? AFFECT original original
Real-World Example: Resume-building system — users duplicate an existing template (default layout,
styling, sections already done). System copies existing template and modifies → Prototype Pattern
BUILDER PATTERN
Purpose: Builder pattern is used to construct complex objects step by step. Separates construction from its
representation — same construction process can create different representations. Useful when object has
multiple configurations or many optional parameters.
Key Participants (Structure)
Role Responsibility
Orchestrates construction — calls [Link]() using the
Director
builder; construct() method drives build
Builder (interface) Declares abstract interface buildPart() for building parts of the Product
Implements Builder interface — buildPart() and getResult():Product;
ConcreteBuilder
creates and assembles parts
The complex object being constructed through multiple buildPart()
Product
calls
Real-World Analogy: Building a custom burger — step by step add bun, patty, cheese, lettuce, sauce.
Each step is separate and the same process can create different configurations.
EXAM ALERT: ESE 2024 Q2(a)(i): 'Scenario: designing meal ordering system for a restaurant —
construct meal objects with customizable components such as main courses, side dishes,
beverages. Which creational design pattern?' → Builder Pattern
MODULE 2: STRUCTURAL PATTERNS
ADAPTER PATTERN
Intent: Converts the interface of a class into another interface that the client expects. Lets classes work
together that otherwise couldn't because of incompatible interfaces. This pattern makes a wrapper
(Adapter) that converts calls from client's expected interface to the existing class's interface.
Problem it Solves
• Client expects a certain interface that is different from what is provided by existing class
• You want to use an existing class but its interface doesn't match what you need
• Cannot modify the third-party/legacy class
Key Participants
Role Description
Client The class that uses the Target Interface (ITarget); calls MakeRequest()
ITarget (interface) The interface that Client expects; Adapter implements this interface
Implements ITarget; wraps Adaptee; translates calls from Client's format to
Adapter
Adaptee's SpecificRequest()
The existing class with incompatible interface (SpecificRequest() — cannot
Adaptee
be modified)
Key Takeaways
• Adapter acts as a bridge between two incompatible interfaces
• No modifications are needed in the existing Adaptee class
• Real example: Existing Android Charger (Type-C) used to charge iPhone (Lightning) using an
Adapter
Adapter vs Proxy — Common Exam Question
Aspect Adapter Proxy
Changes interface — makes
Controls access — surrogate
Main Purpose incompatible interfaces work
for another object
together
Different interface — converts Same interface — client
Interface
to expected interface cannot tell it's a proxy
Integrating legacy/third-party Lazy loading, access control,
Use Case
code logging, caching
EXAM ALERT: ESE 2024 Q3(a)(i): 'Connecting a new payment system to online store — doesn't
match your store's setup. Explain using suitable design pattern.' → Adapter Pattern
FLYWEIGHT PATTERN
Problem it Solves: Reduces memory usage and improves performance by sharing common parts (intrinsic
state) of objects among multiple objects. Useful when there are many similar objects and overhead of
storing redundant data becomes significant.
Intrinsic vs Extrinsic States (QB Q2b — 10 marks)
Aspect Intrinsic State Extrinsic State
Shared state — can be shared
Unique state — unique to each
among multiple flyweight objects;
Definition instance; CANNOT be shared;
INDEPENDENT of context in which
maintained externally by client
they are used
NOT stored inside flyweight;
Stored In INSIDE the flyweight object itself PASSED from outside by client
when needed
Position (X, Y), size, rotation of
Example (Text Font style, color, shape of character
specific character — changes for
Editor) — stays same for all 'A' characters
each occurrence
X and Y position (passed from
Example (Circle) Color (stored inside object, shared)
outside, changes every time)
Stored ONCE, shared by many → Stored by client, NOT in flyweight →
Memory Role
reduces memory keeps flyweight lightweight
Key Components
Component Role
Flyweight Interface Defines interface for flyweight objects; specifies operations flyweight
(Optional) objects must support
Implements Flyweight interface; stores intrinsic (shared) state which is
Concrete Flyweight
independent of context
Manages creation and reuse of flyweight objects; maintains a
Flyweight Factory pool/HashMap of existing flyweights; getFlyweight(key) returns
existing or creates new
Uses flyweight objects; stores and passes extrinsic (context-
Client
dependent) state to flyweights when calling operations
HashMap Mechanism: In Flyweight Pattern, a HashMap stores references to already-created objects.
When client wants an object, they pass a key. If key exists → return reference. If not → create new object,
store in HashMap, return reference.
Memory Calculation Numericals
Text Editor — 50,000 characters Digital Forest — 45,000 objects
Each char: Font(20) + Size(4) + Color(8) + Intrinsic per type: Texture(120KB) +
Value(2) + Pos(8) = 42 bytes Without Model(300KB) + Color(20KB) = 440 KB
Flyweight: 42 x 50,000 = 2,100,000 bytes = 2.1 Extrinsic per obj: X+Y+Z(12B) + Rotation(4B) +
MB With Flyweight: • Shared Scale(4B) = 20 bytes Without Flyweight:
(Font+Size+Color) = 32 bytes (stored ONCE) • 45,000 x 440.02 KB = 19,800,900 KB = ~19.3
Per char (Value+Position) = 10 bytes • Total = GB With Flyweight: • 3 intrinsic objects x 440
(10 x 50,000) + 32 = 500,032 bytes = 0.5 MB KB = 1,320 KB = 1.29 MB • 45,000 x 20 bytes =
Memory Saved: 2.1 MB - 0.5 MB = 1.6 MB 900,000 bytes = 0.86 MB • Total = ~2.15 MB
Memory Saved: ~19.3 GB
EXAM ALERT: TT1 Q2(b): 'Discuss the key components of the Flyweight design pattern and explain
the difference between intrinsic and extrinsic states.' — 10 marks
PROXY PATTERN
Definition: Proxy provides a surrogate or placeholder for another object to control access to it. The proxy
may allow access, deny access, delay loading (lazy initialization), or log activity. ATM Analogy: You don't
directly access bank database. ATM verifies card, PIN, then talks to bank. ATM = Proxy | Bank Server =
Real Object
Key Participants
Role Description
Common interface implemented by both RealSubject and Proxy — e.g.,
Subject Interface
IImage with Display() method
The actual heavy object; contains real functionality but expensive to create
RealSubject
(e.g., loads 500MB image from disk)
Holds reference to RealSubject; controls access; creates RealSubject lazily
Proxy
only when needed
Lazy Loading — Photo Gallery Numerical
Without Proxy (800 images, 5 MB each, 200 With Lazy Loading Proxy (user views 12
ms each) images)
Memory: 800 x 5 MB = 4000 MB = 4 GB Memory: 12 x 5 MB = 60 MB Loading Time: 12
Loading Time: 800 x 200 ms = 160,000 ms = x 200 ms = 2400 ms = 2.4 seconds Memory
160 seconds = 2.67 min Saved: 3940 MB = 3.94 GB
Implementation Issues of Proxy Pattern
• Performance Overhead — Introducing proxy adds additional overhead, especially for lazy
initialization, access control, or logging; impacts performance for frequently accessed objects
• Synchronization — In multithreaded environments, synchronization needed to ensure thread
safety; care needed to handle race conditions or deadlock situations
• Complexity — Multiple proxy classes with different functionalities can increase codebase
complexity
• Resource Management — Proxies may manage resources like network/DB connections; proper
release essential to prevent resource leaks
DECORATOR PATTERN
Motivation: The Decorator pattern is motivated by the need to dynamically add additional behaviors or
responsibilities to objects WITHOUT altering their structure. This adheres to the Open-Closed Principle
(OCP) and Single Responsibility Principle (SRP).
Real-Life Analogy
Coffee Shop: Order basic coffee, then add Milk (+20), Chocolate (+30), Whipped Cream (+15). You didn't
create a new 'MilkChocolateCreamCoffee' class. You wrapped the base coffee with extras. That's
Decorator.
4 Roles of Decorator Pattern
Role Description and Example
Interface for objects that can have responsibilities added dynamically;
1. Component Interface
e.g., ICoffee with GetDescription() and GetCost()
The base object to which decorators add responsibilities; e.g.,
2. Concrete Component
SimpleCoffee: returns 'Simple Coffee', cost = 50
Abstract class implementing Component Interface; stores reference to
3. Base Decorator
a Component object (wrapping); delegates to inner component
Add specific behaviors; MilkDecorator: adds ', Milk' to description and
4. Concrete Decorators
+20 to cost; ChocolateDecorator: adds ', Chocolate' and +30
Applications of Decorator Pattern
• GUI Components — Add borders, scroll bars, tooltips to basic GUI components dynamically
without extensive subclassing
• Input/Output Streams — Add buffering, compression, or encryption to basic streams (Java I/O
streams are a classic example)
• Text Formatting — Apply bold, italic, underline to text strings dynamically by combining multiple
decorators
• Authentication and Authorization — Wrap objects with security checks without compromising
core functionality
Open-Closed Principle: Decorator follows 'Open for extension, Closed for modification'. We did NOT
modify SimpleCoffee. We extended its behavior by wrapping it with Milk, then Chocolate decorators.
EXAM ALERT: ESE 2024 Q3(a)(ii): 'Explain the Decorator pattern and its purpose in software
design. Provide a scenario where the Decorator pattern would be beneficial.' — 10 marks
FACADE PATTERN
Definition: Facade provides a SIMPLIFIED interface to a COMPLEX subsystem. System is complex —
Facade hides complexity — Client sees one simple interface.
Real-Life Analogy
Watching a movie: Turn on streaming device, turn on sound system, start streaming device, dim lights —
OR just 'Book ticket and sit in Movie Hall'. Theatre handles everything internally. Theatre = Facade.
Problem Facade Solves
• Without Facade, client must call: [Link](), [Link](), [Link](), [Link](),
[Link]() — too many interactions, client must know all subsystem details
• With Facade: [Link]() — one simple call that handles everything
• Future adaptation: if theatre adds popcorn automation, client code doesn't change — Facade
absorbs the change
Facade Class Diagram Mapping
UML Element Theatre Example Role
Calls Facade — doesn't know
Client Movie visitor
subsystem details
Provides simplified
TheatreFacade / Theatre
Facade WatchMovie() method;
system
coordinates all subsystems
Complex internals that are
TicketCounter, Lights,
Subsystem classes hidden from the client; do the
Projector, SoundSystem
actual work
COMPOSITE PATTERN
Definition: A structural pattern that allows clients to treat individual objects and compositions of objects
uniformly. Composes objects into TREE STRUCTURES to represent part-whole hierarchies.
How Composite Solves Tree-like Structure Problems
Mechanism How it Helps
Common interface for both individual objects (Leaf) and composite
Uniform Interface
objects (Node) — methods like add(), remove(), getChild(), operation()
Composite objects contain other composites AND individual objects —
Recursive Structure
forms a recursive tree. Represents complex part-whole hierarchies.
Traversal & Clients can traverse/manipulate tree using DFS or BFS. Same
Manipulation operations applied recursively to all elements regardless of type.
From client's perspective, no distinction between individual and
Transparency composite objects. Clients can treat composite as if it were an
individual object.
QUICK REVISION — PATTERN IDENTIFICATION
TT1 Match-Type Questions (Q3 — 5 marks)
Application/Scenario Pattern
A game that instantiates different objects dynamically and
Flyweight
promotes loose coupling
A logging system that ensures only one logger throughout
Singleton
the application, ensures thread safety
External library data in incompatible format — achieve
Adapter
interoperability
Minimize memory usage or computational expenses by
Flyweight
sharing as much as possible with similar objects
Manage access to remote service — authentication,
Proxy
caching, load balancing
E-commerce: multiple payment methods — client should
Factory Method
not directly create payment objects
University ERP: global config shared by all modules — only
Singleton
one config object should exist
Resume-building: duplicate existing template and modify it
Prototype
— creating from scratch is time-consuming
Hospital: (a) Central log file, (b) Different report types, (c) (a) Singleton (b) Factory (c)
Shared report templates Prototype
Meal ordering system — construct meal objects with
Builder
customizable components
Payment gateway integration — third-party API interface
Adapter
doesn't match your application
New system needs to connect to payment gateway —
Adapter
different interface from existing system
All Patterns Quick Reference
Pattern Type One-Line Intent
ONE instance only — private constructor + static
Singleton Creational
getInstance()
Let subclasses decide which class to instantiate —
Factory Method Creational
program to interface
Create FAMILIES of related objects without
Abstract Factory Creational
specifying concrete classes
Construct complex objects step-by-step with Director
Builder Creational
+ ConcreteBuilder
Clone existing objects (MemberwiseClone) instead of
Prototype Creational
creating from scratch
Convert incompatible interface to compatible one —
Adapter Structural
wrapper pattern
Share intrinsic state via HashMap to reduce memory
Flyweight Structural
— extrinsic passed by client
Proxy Structural Surrogate for another object — controls/delays
access (same interface)
Add behavior dynamically by WRAPPING object —
Decorator Structural
Open-Closed Principle
Simplified interface to complex subsystem — hides
Facade Structural
complexity
Tree structures — treat individual objects and
Composite Structural
compositions uniformly
TT1 2024 QB Answer Guide
Q Question Marks Must-Write Points
Purpose of Builder, 4-column
comparison table
Builder pattern purpose + how it differs (Purpose/Construction/Complexity/Fle
Q
from Factory Method and Abstract 10 xibility for all 3 patterns), Builder
1a
Factory structure
(Director+Builder+ConcreteBuilder+Pr
oduct)
Intent (1 instance, global access), 3
Singleton design pattern — intent + implementation steps (private
Q
implementation + advantages and 10 constructor, private static instance,
1b
disadvantages public getInstance()), code, Benefits (3
points), Issues (4 points)
Definition of design patterns, GoF
What are design patterns? List and reference, 3 factors: Problem
Q
explain 3 factors while selecting a 10 Relevance + Scalability/Maintainability
2a
design pattern + Performance Considerations (each
with example)
4 components (FW Interface +
Key components of Flyweight + Concrete FW + FW Factory/HashMap
Q
difference between intrinsic and 10 + Client), Intrinsic vs Extrinsic
2b
extrinsic states comparison table (definition, stored in,
example)
As per answer key: Flyweight,
Singleton (listed as Proxy in some
Q Match applications with corresponding
5 keys), Factory Method, Flyweight,
3 design pattern
Adapter — learn the application
descriptions carefully
EXAM ALERT: ESE FINAL EXAM TOPICS (2024): Factors for selecting DP (10), Creational patterns
examples (5), Builder/Meal scenario (10), Singleton for logging (10), Adapter/payment system (10),
Decorator pattern + scenario (10), Chain of Responsibility (10), Observer pattern (10)