Design Patterns Study Guide
Design Patterns Study Guide
💡 EXAM TIP: MCQ: 'Who defined the classic design patterns?' The Gang of Four (GoF). Their book documented
23 foundational patterns.
Impact Hard to change later (affects everything) Easier to refactor (localised change)
💡 EXAM TIP: Memory trick: Creation = BIRTH of objects. Structural = BODY shape. Behavioral = BEHAVIOUR.
Think: born, shaped, behaves.
4. Singleton Pattern
Simple idea: Ensure only ONE instance of a class exists in the entire system, and provide a global point of access
to it. Like having only one principal in a school — just one, accessible by everyone.
Private constructor The constructor is PRIVATE so nobody Blocks anyone from creating a
outside can call 'new Singleton()' second instance
Public getInstance() The only way to get the instance — Provides controlled global access
creates it on first call, returns same one
always
private static Principal instance = null; Only one instance, kept inside the class
public static Principal getInstance() { Anyone calls this to get the principal
if (instance == null) { First time? Create it.
instance = new Principal();
Output: 'Principal created!' appears ONCE only. p1 == p2 is TRUE. No matter how many times you call
getInstance(), you always get the same object.
Saves resources — only one instance exists Hard to unit test — hidden dependencies
Better than global variables (enforces single instance) Creates tight coupling between classes
💡 EXAM TIP: MCQ: 'Why is Singleton risky in multi-threaded environments?' Two threads could both check 'if
(instance == null)' at the same time and both create a new instance — breaking the guarantee.
5. Builder Pattern
Simple idea: When an object is too complex to build with one big constructor, use a Builder to construct it
piece by piece, step by step. Like ordering a custom sandwich — you choose each ingredient one at a time.
Builder (interface) Lists all the steps to build parts BurgerBuilder: addBun(), addPatty(),
addCheese()
Director Controls the ORDER of steps Chef says: first bun, then patty, then
toppings
Key insight: The Chef (Director) always calls the SAME 3 steps in the SAME order. But VeggieBuilder and
MeatBuilder fill those steps differently — producing different burgers from the same process.
Manages complex object creation cleanly Requires more classes — added complexity
Same steps can produce different representations Overkill for simple objects
Improves readability — each step is named Director-Builder relationship can be confusing initially
💡 EXAM TIP: MCQ: 'What is the role of the Director in Builder?' Controls the ORDER of steps — knows the
sequence but not the details of HOW each step is implemented.
6. Factory Method Pattern
Simple idea: Instead of writing 'new Dog()' or 'new Cat()' directly, you call a factory method and let the subclass
decide what to create. The client doesn't need to know the exact class.
Open-Closed Principle: Code should be OPEN for extension (add new types) but CLOSED for modification (don't
change existing code).
Product (interface) Defines what all created objects Animal interface — has speak() method
can do
ConcreteProduct The actual object being created Dog class, Cat class
Creator (abstract class) Declares the factory method AnimalFactory — declares createAnimal()
// ConcreteProducts
[Link]("Woof!");
}
[Link]("Meow!");
// ConcreteCreators
Key insight: makeAnimalSpeak() works with ANY animal — it never says 'new Dog()'. To add a Fish class, you
just add FishFactory. Zero changes to existing code.
Purpose Create one of many RELATED objects Construct one COMPLEX object step
by step
Client controls steps? No — just calls factory and gets Yes — via Director controlling the
result order
Real-world analogy Ordering from a menu (pick type, Customising a car (specify each
kitchen makes it) feature one by one)
💡 EXAM TIP: MCQ: 'Which pattern lets you add new types without modifying existing code?' Factory Method —
supports Open-Closed Principle by adding new ConcreteCreator subclasses.
7. Proxy Pattern
Simple idea: A Proxy is a STAND-IN or GATEKEEPER for another object. The client talks to the proxy, which
controls access to the real object — adding security, performance, or lazy loading.
Types of Proxies
Proxy Type What it does Real-World Example
Virtual Proxy Delays creation of expensive object Thumbnail shown first; full image loads
until actually needed only when clicked
Protection Proxy Checks permissions before allowing Bank checking if user has admin rights
access
Remote Proxy Represents an object on a different API client talking to a remote server
machine
Smart Proxy Adds extra behaviour like logging or Logging all database calls automatically
caching
Proxy — 3 Components
Component Role
Subject (interface) Shared interface that both Proxy and RealSubject implement
Proxy Controls access — same interface so client can't tell the difference
if ([Link](b)) {
Key insight: The client uses 'Internet internet' — it doesn't know or care if it's a proxy or real. The proxy silently
adds access control logic without changing the real object.
Controls access to sensitive or expensive objects Adds more classes — increases complexity
Reduces unnecessary resource usage (lazy loading) Can add slight performance overhead
💡 EXAM TIP: MCQ: The Proxy and RealSubject share the SAME interface — the client cannot tell it's talking to a
proxy. This is the defining feature of Proxy.
8. Adapter Pattern
Simple idea: An Adapter is like a power plug converter. You have a device with a UK plug and a US socket — the
adapter makes them compatible. In software: it makes two incompatible interfaces work together.
Adapter — 4 Components
Component Role Example
Target (interface) The interface YOUR code MediaPlayer with play(String filename)
expects
Adaptee The existing class with a OldPlayer with playFile(String path, int volume)
DIFFERENT interface
Client Your code that uses the Target Main class calling [Link]("song.mp3")
interface
Key insight: The client calls play(filename) — it has no idea the old system needs a volume parameter too. The
adapter quietly handles the translation.
Adapter vs Proxy — They Look Similar But Are Different
Aspect Adapter Pattern Proxy Pattern
Interface to client DIFFERENT from the adaptee's SAME as the real object's interface
interface
Real-world analogy Power plug converter (UK to US) Security guard (controls who enters)
💡 EXAM TIP: MCQ trick: Same interface = Proxy. Different interface = Adapter. That's the fastest way to tell
them apart.
9. Bridge Pattern
Simple idea: Bridge separates WHAT something does (abstraction) from HOW it does it (implementation) — so
both can change independently. Like a TV remote (abstraction) that can control any TV brand
(implementation).
With Bridge: 2 shapes + 2 colours = 4 classes total — and adding Triangle only adds 1 class, adding Green only
adds 1 class. No explosion!
Bridge — 4 Components
Component Role Example
Abstraction High-level interface — defines Shape — has draw() which uses a colour
WHAT can be done
Implementor (interface) Defines HOW the implementation Color interface with fill() method
works
Concrete Implementor Provides the actual low-level Red, Blue
behaviour
// Concrete Implementors
[Link]("filled Red");
[Link]("filled Blue");
// Refined Abstractions
class Circle extends Shape {
Circle(Color c) { super(c); }
void draw() {
[Link]("Circle ");
Square(Color c) { super(c); }
void draw() {
[Link]("Square ");
Key insight: Color is COMPOSED into Shape (not inherited). Shape calls [Link]() without knowing if it's Red or
Blue. This is 'prefer composition over inheritance.'
Improves extensibility — add shapes or colours Overengineering risk if only one implementation exists
independently
💡 EXAM TIP: MCQ: 'What does Bridge prefer over inheritance?' COMPOSITION — the Shape CONTAINS a Color
reference rather than inheriting from ColoredShape. This is the core principle.
Singleton Creational Need exactly ONE Private constructor + One principal for the whole
instance static getInstance() school
Proxy Structural Direct access is costly Surrogate controls School internet filter blocking
or unsafe access — same bad sites
interface
Who defined the classic 23 design patterns? The Gang of Four (GoF)
What are the 3 categories of design patterns? Creational (create), Structural (compose), Behavioral
(communicate)
Architectural vs Design pattern — which is harder to Architectural — affects the entire system
change?
Why is Singleton's constructor private? To prevent outside code from using 'new ClassName()'
to create extra instances
Why is Singleton risky in multi-threaded code? Two threads may simultaneously pass the null check
and both create new instances
What is the role of the Director in Builder? Controls the ORDER of construction steps — same
sequence every time
Factory Method vs Builder — which builds complex Builder — Factory creates simple objects; Builder
objects? constructs complex ones step by step
What principle does Factory Method support? Open-Closed Principle — extend by adding new
ConcreteCreator classes
What does a Proxy share with RealSubject? The SAME interface — client cannot tell it's talking to a
proxy
Name the 4 types of Proxy Virtual (lazy loading), Protection (access control),
Remote (network), Smart (logging/caching)
What problem does Adapter solve? Interface MISMATCH — makes incompatible interfaces
work together
Adapter vs Proxy — key interface difference? Adapter: DIFFERENT interface from adaptee. Proxy:
SAME interface as real object.
Adapter vs Proxy real-world analogy? Adapter = power plug converter. Proxy = security
guard.
What is 'class explosion' and which pattern solves it? Exponential growth of classes from multiple
inheritance dimensions — Bridge solves it
What does Bridge prefer over inheritance? COMPOSITION — abstraction holds a reference to
implementor
In Singleton, what happens on the second call to The EXISTING instance is returned — no new object is
getInstance()? created
In the school internet proxy example, what plays the RealInternet — the actual internet access object
RealSubject role?
In Builder, what calls the steps in order? The Director — it orchestrates the build without
knowing implementation details
What is the defining output of the Factory Method A Product object — the client only knows it as the
pattern? interface type, not the concrete class
Does Bridge use inheritance or composition to COMPOSITION — Shape contains a Color, it does not
connect abstraction to implementation? extend/inherit Color