0% found this document useful (0 votes)
3 views17 pages

Design Patterns Study Guide

Software development design pattern java code

Uploaded by

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

Design Patterns Study Guide

Software development design pattern java code

Uploaded by

Aniruddha Manab
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SOFTWARE DESIGN PATTERNS

Easy Study Guide — Simple Language · Code Examples · MCQ Hints

1. What is a Design Pattern?


Simple idea: A design pattern is a PROVEN, REUSABLE solution to a problem that keeps coming up in software
design. Instead of reinventing the wheel, you use a known blueprint that works.

Think of it like building construction:


• Problem: How to safely transfer loads from a structure to the ground
• Solution (pattern): Columns → Beams → Slabs → Foundation
• Variations: strip footing, raft foundation, pile foundation — same idea, different implementations
• Software equivalent: Layered Architecture pattern

Key characteristics of design patterns:


• Language-independent — they are conceptual, not tied to Java or Python
• Higher-level than syntax — about structure and collaboration, not code details
• About structure, behavior, or object collaboration
• Classic source: Gang of Four (GoF) book — the original 23 design patterns

💡 EXAM TIP: MCQ: 'Who defined the classic design patterns?' The Gang of Four (GoF). Their book documented
23 foundational patterns.

2. Architectural Patterns vs Design Patterns


Simple distinction: Architectural patterns = the WHOLE building's blueprint. Design patterns = how individual
ROOMS are designed.

Aspect Architectural Pattern Design Pattern

Scope Entire system Part of the system

Level High-level structure Low-level / mid-level design

Focus System organisation and responsibilities Object and class collaboration

Impact Hard to change later (affects everything) Easier to refactor (localised change)

Concern Scalability, deployment, communication Flexibility, reuse, maintainability

Examples Layered, MVC, Microservices Factory, Observer, Strategy, Singleton


💡 EXAM TIP: MCQ: 'Which has greater impact on the system?' Architectural patterns — they are hard to change
once decided. Design patterns are easier to refactor.

3. The 3 Categories of Design Patterns


Every design pattern falls into one of 3 categories. You MUST know which pattern belongs to which category:

Category Concern Simple Question it Answers Examples

Creational Object creation How do we CREATE objects in a Singleton, Factory Method,


flexible way? Abstract Factory, Builder,
Prototype

Structural Object composition How do we COMBINE classes Adapter, Decorator, Facade,


and objects into larger Composite, Proxy, Bridge,
structures? Flyweight

Behavioral Object How do objects TALK to each Observer, Strategy, Command,


communication other and share responsibility? Iterator, State, Template
Method

💡 EXAM TIP: Memory trick: Creation = BIRTH of objects. Structural = BODY shape. Behavioral = BEHAVIOUR.
Think: born, shaped, behaves.

CREATIONAL PATTERNS — How Objects Are Created

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.

The Problem Singleton Solves


Some resources should only exist once:
• Database connection — you don't want 100 separate connections
• Logging system — one log file for the whole application
• Configuration manager — one set of settings, not many
• Print spooler — one queue for all printers

How Singleton Works — 3 Key Components


Component What it is Why it's needed
Private static instance A variable inside the class that holds THE Keeps the single instance stored
one object inside the class

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

Simplest Possible Code Example


Scenario: A school has ONE principal. No matter who asks, they always get the same principal object.

Code What it means


class Principal { Start of our Singleton class
// Step 1: store the one instance

private static Principal instance = null; Only one instance, kept inside the class

// Step 2: block outside creation

private Principal() { Private = nobody outside can say 'new


Principal()'
[Link]("Principal created!");

// Step 3: the one way to get it

public static Principal getInstance() { Anyone calls this to get the principal
if (instance == null) { First time? Create it.
instance = new Principal();

return instance; Every time: return the same one


}

public void greet() {

[Link]("Hello from the


Principal!");
}

// --- Using it ---


Principal p1 = [Link](); Gets (creates) the principal
Principal p2 = [Link](); Gets the SAME principal
[Link](); Hello from the Principal!
[Link](p1 == p2); Prints: true — they are the SAME object!

Output: 'Principal created!' appears ONCE only. p1 == p2 is TRUE. No matter how many times you call
getInstance(), you always get the same object.

Singleton Pros Singleton Cons

Saves resources — only one instance exists Hard to unit test — hidden dependencies

Provides controlled global access Risky in multi-threaded environments

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.

The Problem Builder Solves


• Imagine a Burger object: bun, patty, cheese, lettuce, sauce, pickles, onions...
• A constructor like: new Burger(bun, patty, cheese, lettuce, sauce, pickles) is unreadable
• Different burgers (veggie, cheese, double) need the same STEPS but different results
• Builder lets you build it step by step and get different results from the same process

Builder Pattern — 4 Components


Component Role Burger Example

Builder (interface) Lists all the steps to build parts BurgerBuilder: addBun(), addPatty(),
addCheese()

ConcreteBuilder Implements each step for a specific VeggieBurgerBuilder,


type CheeseBurgerBuilder

Director Controls the ORDER of steps Chef says: first bun, then patty, then
toppings

Product The final built object The finished Burger


Simplest Possible Code Example
Scenario: Build a simple Burger step by step. Same steps, but a VeggieBuilder makes a veggie burger and a
MeatBuilder makes a meat burger.

Code What it means


// The Product

class Burger { The final object we're building


String bun, patty, sauce; Parts of the burger
public String toString() {

return bun + " + " + patty + " + " + sauce;

// The Builder interface (defines steps)

interface BurgerBuilder { Blueprint — what steps exist


void buildBun(); Step 1
void buildPatty(); Step 2
void buildSauce(); Step 3
Burger getResult(); Return the finished burger
}

// ConcreteBuilder 1 — Veggie Burger

class VeggieBuilder implements BurgerBuilder {

Burger burger = new Burger();

public void buildBun() { [Link] =


"Sesame Bun"; }
public void buildPatty() { [Link] =
"Veggie Patty"; }
public void buildSauce() { [Link] =
"Mayo"; }
public Burger getResult() { return burger; }

// ConcreteBuilder 2 — Meat Burger

class MeatBuilder implements BurgerBuilder {

Burger burger = new Burger();

public void buildBun() { [Link] =


"Brioche Bun"; }
public void buildPatty() { [Link] =
"Beef Patty"; }
public void buildSauce() { [Link] = "BBQ
Sauce"; }
public Burger getResult() { return burger; }

// Director — controls the order

class Chef { The Director


void make(BurgerBuilder b) { Same steps every time
[Link](); Step 1 always first
[Link](); Step 2 always second
[Link](); Step 3 always last
}

// --- Using it ---

Chef chef = new Chef();

VeggieBuilder vb = new VeggieBuilder();

[Link](vb); Chef calls same 3 steps


[Link]([Link]()); Sesame Bun + Veggie Patty + Mayo

MeatBuilder mb = new MeatBuilder();

[Link](mb); SAME steps, different builder


[Link]([Link]()); Brioche Bun + Beef Patty + BBQ Sauce

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.

Builder Pros Builder Cons

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.

The Problem Factory Method Solves


• Code that directly creates objects (new Truck(), new Ship()) is tightly coupled
• Adding a new type means changing existing code — violates Open-Closed Principle
• Large if-else blocks that decide which object to create become hard to maintain

Open-Closed Principle: Code should be OPEN for extension (add new types) but CLOSED for modification (don't
change existing code).

Factory Method — 4 Components


Component Role Animal Example

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()

ConcreteCreator Overrides factory method to DogFactory returns Dog; CatFactory returns


create a specific product Cat

Simplest Possible Code Example


Scenario: An animal shelter creates different animals. The client just asks for 'an animal' — it doesn't need to
know if it's a dog or cat.

Code What it means


// Product interface

interface Animal { All animals can do this


void speak(); The common behaviour
}

// ConcreteProducts

class Dog implements Animal {

public void speak() {

[Link]("Woof!");
}

class Cat implements Animal {

public void speak() {

[Link]("Meow!");

// Creator — declares the factory method

abstract class AnimalFactory {

abstract Animal createAnimal(); Subclass decides what to create

// Uses the factory method (doesn't know what


animal)
void makeAnimalSpeak() {

Animal a = createAnimal(); Calls factory method


[Link](); Works with ANY animal
}

// ConcreteCreators

class DogFactory extends AnimalFactory {

Animal createAnimal() { return new Dog(); } This one creates Dogs


}

class CatFactory extends AnimalFactory {

Animal createAnimal() { return new Cat(); } This one creates Cats


}

// --- Using it ---

AnimalFactory factory = new DogFactory(); Choose which factory


[Link](); Prints: Woof!

factory = new CatFactory(); Switch factory


[Link](); Prints: Meow!
// To add a Bird: just add BirdFactory — no Open-Closed!
existing code changes!

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.

Factory Method vs Builder — Side by Side


Aspect Factory Method Builder Pattern

Purpose Create one of many RELATED objects Construct one COMPLEX object step
by step

Focus TYPE selection — which class to STEP-BY-STEP construction — how to


create build it

Object complexity Usually simple Usually complex (many parts)

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.

STRUCTURAL PATTERNS — How Classes and Objects Are Composed

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

RealSubject The actual object with full functionality

Proxy Controls access — same interface so client can't tell the difference

Simplest Possible Code Example


Scenario: A student wants to access the internet. A SchoolProxy checks if the website is allowed before letting
the request through to the real internet.

Code What it means


// Subject interface

interface Internet { Both real and proxy implement this


void browse(String site);

// RealSubject — actual internet access

class RealInternet implements Internet { The real object


public void browse(String site) {

[Link]("Loading: " + site);

// Proxy — controls access

class SchoolProxy implements Internet { Same interface as RealInternet


private RealInternet real = new Has a reference to the real object
RealInternet();
private String[] blocked = Blocked list
{"[Link]","[Link]"};

public void browse(String site) {

for (String b : blocked) {

if ([Link](b)) {

[Link]("BLOCKED: " + site); Protection logic


return; Stop here — don't pass to real object
}

[Link](site); Allowed — forward to real object


}

// --- Using it ---

Internet internet = new SchoolProxy(); Client uses the proxy


[Link]("[Link]"); Loading: [Link]
[Link]("[Link]"); BLOCKED: [Link]
[Link]("[Link]"); Loading: [Link]

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.

Proxy Pros Proxy Cons

Controls access to sensitive or expensive objects Adds more classes — increases complexity

Reduces unnecessary resource usage (lazy loading) Can add slight performance overhead

Adds functionality without changing the real object

💡 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

Adapter Wraps Adaptee, implements MediaAdapter converts the call format


Target, translates calls

Client Your code that uses the Target Main class calling [Link]("song.mp3")
interface

Simplest Possible Code Example


Scenario: Your app uses a MediaPlayer interface. You also have an old OldPlayer class with a completely
different method signature. Adapter bridges them.

Code What it means


// Target — what YOUR code expects

interface MediaPlayer { Your app is built around this


void play(String filename); Clean, simple interface
}

// Adaptee — the OLD class you can't change

class OldPlayer { Existing class — different interface


void playFile(String path, int volume) { Different method name!
[Link]("Playing " + path + Different parameters!
" at volume " + volume);

// Adapter — the translator

class MediaAdapter implements MediaPlayer { Implements what your app expects


private OldPlayer old = new OldPlayer(); Wraps the old class

public void play(String filename) { Receives the new-style call


[Link](filename, 80); Translates to old-style call
} Adds missing parameter (default volume 80)
}

// --- Using it ---

MediaPlayer player = new MediaAdapter(); Client uses Target interface


[Link]("song.mp3"); Playing song.mp3 at volume 80
// Client has NO idea OldPlayer exists! Totally unaware of adaptation

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

Primary intent Make incompatible interfaces work Control access to an object


together

Problem solved Interface MISMATCH between two Access, performance, or security


classes concern

Interface to client DIFFERENT from the adaptee's SAME as the real object's interface
interface

Focus Compatibility — translation Control — security, caching, lazy


loading

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

The Problem Bridge Solves — Class Explosion


Without Bridge — imagine Shapes AND Colours:
• 2 shapes (Circle, Square) x 2 colours (Red, Blue) = 4 classes already
• Add Triangle: now 6 classes. Add Green: now 9 classes
• The classes MULTIPLY with every new dimension — this is called class explosion

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

Refined Abstraction Extends abstraction with specific Circle, Square


shapes

Implementor (interface) Defines HOW the implementation Color interface with fill() method
works
Concrete Implementor Provides the actual low-level Red, Blue
behaviour

Simplest Possible Code Example


Scenario: Shapes can be drawn in different colours. Without Bridge: RedCircle, BlueCircle, RedSquare,
BlueSquare — 4 classes! With Bridge: Shape + Color hierarchies, any combination works with only 4 classes
total.

Code What it means


// Implementor interface — the HOW side

interface Color { The 'implementation' hierarchy


void fill(); HOW to apply colour
}

// Concrete Implementors

class Red implements Color {

public void fill() {

[Link]("filled Red");

class Blue implements Color {

public void fill() {

[Link]("filled Blue");

// Abstraction — the WHAT side

abstract class Shape { The 'abstraction' hierarchy


protected Color color; BRIDGE: holds a reference to Color
Shape(Color color) { Color is injected (not inherited!)
[Link] = color;

abstract void draw(); WHAT the shape does


}

// Refined Abstractions
class Circle extends Shape {

Circle(Color c) { super(c); }

void draw() {

[Link]("Circle ");

[Link](); Delegates HOW to the Color object


[Link]();

class Square extends Shape {

Square(Color c) { super(c); }

void draw() {

[Link]("Square ");

[Link](); Same delegation


[Link]();

// --- Using it ---

Shape s1 = new Circle(new Red()); Mix and match freely!


Shape s2 = new Square(new Blue()); Any combination works
Shape s3 = new Circle(new Blue()); No extra classes needed
[Link](); Circle filled Red
[Link](); Square filled Blue
[Link](); Circle filled Blue
// Add Triangle? Just 1 new class. Add Green? No explosion!
Just 1 new class.

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.'

Bridge Pros Bridge Cons

Avoids class explosion More abstractions — design harder to understand


initially

Improves extensibility — add shapes or colours Overengineering risk if only one implementation exists
independently

Supports Open-Closed Principle

Runtime flexibility — swap implementations at


runtime

💡 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.

10. All Patterns — Quick Comparison


Pattern Category Problem it Solves Key Idea Simplest Analogy

Singleton Creational Need exactly ONE Private constructor + One principal for the whole
instance static getInstance() school

Builder Creational Object too complex Step-by-step Ordering a custom burger


for one constructor construction with ingredient by ingredient
Director

Factory Creational Tight coupling to Subclass decides Animal shelter creates


Method concrete classes which object to animal — client picks type
create

Proxy Structural Direct access is costly Surrogate controls School internet filter blocking
or unsafe access — same bad sites
interface

Adapter Structural Two incompatible Translate one UK plug into US socket


interfaces need to interface into converter
work together another

Bridge Structural Class explosion from Separate abstraction TV remote (abstraction) +


multiple dimensions from any TV brand
implementation (implementation)

MCQ QUICK-FIRE CHEAT SHEET — DESIGN PATTERNS

Question / Scenario Correct Answer

What is a design pattern? A proven, reusable solution to a recurring design


problem in a given context

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?

Which pattern ensures only one instance exists? Singleton

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

Bridge pattern — name the 4 components Abstraction, Refined Abstraction, Implementor


(interface), Concrete 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

Patterns make you a smarter designer — good luck!

You might also like