Learn
B3.2.5 | DESIGN PATTERNS (HL ONLY)
01 | THE SAME DESIGN PROBLEM KEEPS RETURNING
You are building a quiz app. Several screens need the same settings, different channels need different notification objects, and a score change should update both a display and a history log. These are three different problems, but other programmers have solved similar problems many times.
A design pattern is a reusable approach to a recurring design problem. It describes how responsibilities and object relationships can be arranged. It is a guide to a solution, not a complete program to paste into every project.
This lesson explores singleton, factory and observer. For each, identify the problem first, follow a small working implementation and then explain the benefit and limitations.
02 | MATCH THE PATTERN TO THE PROBLEM
| Problem | Pattern | Central idea |
|---|---|---|
| Ordinary callers should use one shared settings instance | Singleton | Control instance creation and provide access to the shared object |
| A caller needs a suitable notice without choosing a concrete class itself | Factory | Move product creation behind a creation operation |
| Several objects should react when a score changes | Observer | Let interested objects subscribe for notifications |
A singleton mainly concerns instance creation and shared access. A factory concerns how a caller obtains an appropriate object. Observer concerns communication after something changes. They solve different problems and can appear together without being interchangeable.
The usual categories are creational for singleton and factory approaches, and behavioural for observer. Knowing a category can help organise ideas, but an explanation still needs the actual mechanism.
03 | SINGLETON: WHY ONE SHARED INSTANCE?
Suppose every screen reads an AppSettings object containing the chosen theme. If each screen constructs separate settings and edits only its own copy, the interface may become inconsistent. A singleton design controls ordinary construction so callers obtain the same instance through a defined access route.
One instance does not mean one reference. Many variables can refer to the same settings object. A theme change through one reference is visible through another because both refer to the same object.
The scope matters. A singleton normally controls one instance within its intended runtime context, not one object across all computers, server processes or deployments. A website with several worker processes does not gain a shared cross-process settings store simply by using this pattern.
04 | PYTHON: CONTROL OBJECT CREATION
class AppSettings:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._theme = "light"
return cls._instance
@property
def theme(self):
return self._theme
def set_theme(self, theme):
if theme not in ("light", "dark"):
raise ValueError("Theme must be light or dark")
self._theme = theme
__new__ is the Python method responsible for creating or returning an instance. On the first ordinary call, this implementation obtains an object through super().__new__(cls), stores it in the class attribute _instance and gives it the initial theme. Later calls return the stored reference.
This example deliberately has no __init__ method. Repeated class calls can run __init__ again even when __new__ returns an existing instance, so resetting the theme there without a guard would lose earlier changes. Initialization here happens only inside the first-creation branch.
Use this as a small single-threaded teaching example for this class, not as a universal Python singleton framework. It does not address concurrent first access, subclass behaviour or deliberate bypasses of the intended construction route.
05 | TRACE THE SHARED IDENTITY
first = AppSettings()
second = AppSettings()
print(first is second)
# True
first.set_theme("dark")
print(second.theme)
# dark
third = AppSettings()
print(third.theme)
# dark
Run this after the AppSettings definition. Python is checks object identity. first and second are two references to one settings instance. Updating through first changes what second reads. Obtaining third does not reset the existing theme.
This differs from merely storing a class variable on an otherwise ordinary class. A class counter can be shared while many instances still exist. The singleton intention is to control the instance obtained by normal callers.
06 | JAVA: PRIVATE CONSTRUCTOR, SHARED ACCESS
final class AppSettings {
private static final AppSettings INSTANCE = new AppSettings();
private String theme = "light";
private AppSettings() { }
public static AppSettings getInstance() {
return INSTANCE;
}
public String getTheme() {
return theme;
}
}
The private constructor prevents ordinary external new AppSettings() calls. A static final field holds the one eagerly created instance for this class, and getInstance returns it. final on the class prevents subclassing in this example.
The complete Java program later adds a validated theme setter. Class initialization manages construction of this eager instance, but shared mutable state still requires its own concurrency policy if several threads access it. A safe construction mechanism does not automatically make all later operations thread-safe.
07 | WHEN SINGLETON HELPS AND WHEN IT HURTS
Singleton can provide a controlled access route when a genuinely unique coordinator is required in the intended scope. However, globally accessible mutable state can hide dependencies. A test that changes the theme may affect the next test unless state is deliberately restored.
A simpler alternative is often to create one ordinary settings object at startup and pass it to the screens that need it. This is dependency injection: providing a dependency rather than making each caller locate it globally. It gives shared identity without necessarily enforcing a singleton class.
Do not make each user’s account or quiz attempt a singleton. Those represent many independent entities. In a multi-user service, mixing their mutable state into one shared object could produce incorrect cross-user behaviour. Choose the pattern from the requirement, not because a class sounds important.
08 | FACTORY: MOVE CREATION OUT OF THE CALLER
The app can preview a notice as email text or screen text. The caller knows the chosen channel, but it should not need to import and select every concrete notice class at every point where a preview is created.
A factory centralises object creation behind an operation such as create_notice(kind). The caller asks for the required product, then uses the common render(text) operation. Creation decisions are separated from the work the caller wants to do with the product.
The factory still needs to know which concrete classes it can create. The dependency has been moved into a suitable creation unit, not magically eliminated from the program.
09 | DEFINE PRODUCTS WITH A COMMON INTERFACE
from abc import ABC, abstractmethod
class Notice(ABC):
@abstractmethod
def render(self, text):
pass
class EmailNotice(Notice):
def render(self, text):
return "Email: " + text
class ScreenNotice(Notice):
def render(self, text):
return "Screen: " + text
Notice establishes the operation that the caller expects. Both concrete classes return formatted strings from render(text). No messages are actually sent. The classes reuse the abstract-interface idea from the earlier lesson.
A factory becomes especially useful when the products can be used through a common contract. If every product required unrelated caller logic, simply centralising constructors would offer less benefit.
10 | IMPLEMENT A SIMPLE FACTORY
def create_notice(kind):
if kind == "email":
return EmailNotice()
if kind == "screen":
return ScreenNotice()
raise ValueError("Unknown notice kind")
notice = create_notice("email")
print(notice.render("Meeting at 16:00"))
# Email: Meeting at 16:00
The decision lives in one function. return EmailNotice() constructs a concrete object and sends its reference back to the caller. The caller then invokes render without another test for the class name. Unknown channel values raise an explicit error rather than silently choosing an arbitrary default.
This is a simple factory example. The more specific Factory Method pattern lets creator subclasses override a creation operation. Abstract Factory creates families of related products. Those are related factory approaches, but this selection function should not be mislabelled as a complete implementation of either specialised pattern.
11 | A COMPLETE PYTHON FACTORY EXAMPLE
Save the definitions below in factory_demo.py. After them, add the two calling lines shown immediately below the definitions. The factory returns a new instance on each valid request in this implementation; factories do not inherently require either new or shared instances.
from abc import ABC, abstractmethod
class Notice(ABC):
@abstractmethod
def render(self, text):
pass
class EmailNotice(Notice):
def render(self, text):
return "Email: " + text
class ScreenNotice(Notice):
def render(self, text):
return "Screen: " + text
def create_notice(kind):
if kind == "email":
return EmailNotice()
if kind == "screen":
return ScreenNotice()
raise ValueError("Unknown notice kind")
notice = create_notice("screen")
print(notice.render("Quiz starts now"))
# Screen: Quiz starts now
Try changing screen to email. The caller’s render call stays the same. To add AppNotice, supply another compatible product and extend the creation operation. This simple factory still needs an edit when a new recognised kind is added.
12 | JAVA FACTORY AND THE CALLER
interface Notice {
String render(String text);
}
class EmailNotice implements Notice {
public String render(String text) { return "Email: " + text; }
}
class ScreenNotice implements Notice {
public String render(String text) { return "Screen: " + text; }
}
class NoticeFactory {
public static Notice create(String kind) {
if ("email".equals(kind)) return new EmailNotice();
if ("screen".equals(kind)) return new ScreenNotice();
throw new IllegalArgumentException("Unknown notice kind");
}
}
// Inside main:
Notice notice = NoticeFactory.create("email");
System.out.println(notice.render("Hello"));
The declared return type is the common Notice interface. The actual object is an EmailNotice or ScreenNotice. The static creation method is convenient here, but factories do not universally have to be static methods.
Returning a common interface makes the caller less dependent on a concrete class. It does not prevent an error if a product violates the promised behaviour. Test both product creation and the operations that callers use.
13 | OBSERVER: ONE CHANGE, SEVERAL REACTIONS
A quiz score changes. The screen should display the new value, and a history log should record it. Later, a teacher dashboard might also need updates. Hard-coding every possible destination directly into the score-update logic would make that logic grow whenever a new destination appears.
Observer establishes a one-to-many notification relationship. A subject, also called a publisher in this context, maintains interested observers. Observers subscribe, the subject changes, and the subject calls a common update operation on its current observers.
The subject knows the notification contract rather than the internal display or logging instructions. An observer can unsubscribe when it no longer needs notifications.
14 | VISUALISE THE SUBJECT AND OBSERVERS
The publisher does not have to keep asking each observer whether it wants the latest score. Subscription records that interest. Conversely, an observer does not need to repeatedly poll the score to discover every change.
15 | BUILD THE OBSERVERS FIRST
class TextDisplay:
def __init__(self):
self.messages = []
def update(self, score):
self.messages.append(f"Display: {score}")
class HistoryLog:
def __init__(self):
self.entries = []
def update(self, score):
self.entries.append(score)
Both objects support update(score), but their reactions differ. One stores display messages, the other stores numeric history entries. We collect values instead of drawing a real interface so the result is easy to inspect and test.
These Python observers use a compatible operation without a required common superclass. The Java version later declares a ScoreObserver interface. Both approaches express the common notification contract.
16 | BUILD THE SUBJECT AND SUBSCRIPTION LIST
class ScoreBoard:
def __init__(self):
self._score = 0
self._observers = []
def subscribe(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def unsubscribe(self, observer):
if observer in self._observers:
self._observers.remove(observer)
Each ScoreBoard has its own observer list. subscribe avoids registering the same observer twice in this example. unsubscribe removes a registered observer and does nothing if it is already absent. The complete class below adds score access and notifications.
Subscribing does not send an initial score in this design. Some interfaces need an immediate initial refresh; that is an additional policy which should be stated and implemented deliberately. A pattern describes the structure without dictating every event rule.
17 | CHANGE STATE, THEN NOTIFY
def set_score(self, score):
if type(score) is not int or score < 0:
raise ValueError("Score must be a non-negative integer")
if score == self._score:
return False
self._score = score
for observer in tuple(self._observers):
observer.update(self._score)
return True
This method belongs inside ScoreBoard. First validate the request. Then ignore an unchanged score. Next store the new state and call update on each observer. Updating state before notifying ensures a subscriber reading the subject sees the new score.
tuple(self._observers) makes a snapshot of the notification list for this dispatch. If a subscription changes during a callback, it affects later dispatches rather than changing the current loop’s membership snapshot.
Calls here are synchronous: each update runs before the loop proceeds. There is no background thread or message queue. The example assumes observers do not re-enter set_score and that update completes normally.
18 | A COMPLETE PYTHON OBSERVER PROGRAM
Save this as observer_demo.py and click Run. Follow the registration statements before predicting the final display and history contents.
class ScoreBoard:
def __init__(self):
self._score = 0
self._observers = []
@property
def score(self):
return self._score
def subscribe(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def unsubscribe(self, observer):
if observer in self._observers:
self._observers.remove(observer)
def set_score(self, score):
if type(score) is not int or score < 0:
raise ValueError("Score must be a non-negative integer")
if score == self._score:
return False
self._score = score
for observer in tuple(self._observers):
observer.update(self._score)
return True
class TextDisplay:
def __init__(self):
self.messages = []
def update(self, score):
self.messages.append(f"Display: {score}")
class HistoryLog:
def __init__(self):
self.entries = []
def update(self, score):
self.entries.append(score)
board = ScoreBoard()
display = TextDisplay()
history = HistoryLog()
board.subscribe(display)
board.subscribe(history)
board.set_score(3)
board.unsubscribe(history)
board.set_score(5)
print(board.score)
print(display.messages)
print(history.entries)
The output is 5, then ['Display: 3', 'Display: 5'], then [3]. HistoryLog receives the first score change but is unsubscribed before the second. TextDisplay stays subscribed and receives both.
Setting the same score again returns False and produces no notification. Invalid requests raise ValueError before changing state. In this simple implementation, an observer exception propagates and can stop the remaining callbacks after the score has already changed; production systems need a deliberate error policy.
19 | STEP THROUGH SUBSCRIBE, NOTIFY AND UNSUBSCRIBE
Predict which objects receive each event. The trace uses results from the Python implementation and shows both subscriber membership and recorded output. Watch what happens when a value is unchanged or invalid.
20 | A COMPLETE JAVA PROGRAM FOR ALL THREE PATTERNS
Save this as PatternsExample.java and run main. The example uses standard collections and needs no additional packages. It demonstrates shared settings identity, factory creation and observer notifications in the same small application.
import java.util.ArrayList;
import java.util.List;
final class AppSettings {
private static final AppSettings INSTANCE = new AppSettings();
private String theme = "light";
private AppSettings() { }
public static AppSettings getInstance() { return INSTANCE; }
public String getTheme() { return theme; }
public void setTheme(String theme) {
if (!"light".equals(theme) && !"dark".equals(theme)) {
throw new IllegalArgumentException("Theme must be light or dark");
}
this.theme = theme;
}
}
interface Notice {
String render(String text);
}
class EmailNotice implements Notice {
public String render(String text) { return "Email: " + text; }
}
class ScreenNotice implements Notice {
public String render(String text) { return "Screen: " + text; }
}
class NoticeFactory {
public static Notice create(String kind) {
if ("email".equals(kind)) return new EmailNotice();
if ("screen".equals(kind)) return new ScreenNotice();
throw new IllegalArgumentException("Unknown notice kind");
}
}
interface ScoreObserver {
void update(int score);
}
class ScoreBoard {
private int score = 0;
private final List<ScoreObserver> observers = new ArrayList<>();
public int getScore() { return score; }
public void subscribe(ScoreObserver observer) {
if (!observers.contains(observer)) observers.add(observer);
}
public void unsubscribe(ScoreObserver observer) {
observers.remove(observer);
}
public boolean setScore(int value) {
if (value < 0) throw new IllegalArgumentException("Negative score");
if (value == score) return false;
score = value;
for (ScoreObserver observer : new ArrayList<>(observers)) {
observer.update(score);
}
return true;
}
}
class TextDisplay implements ScoreObserver {
public void update(int score) { System.out.println("Display: " + score); }
}
class HistoryLog implements ScoreObserver {
private final List<Integer> entries = new ArrayList<>();
public void update(int score) { entries.add(score); }
public List<Integer> getEntries() { return new ArrayList<>(entries); }
}
public class PatternsExample {
public static void main(String[] args) {
AppSettings first = AppSettings.getInstance();
AppSettings second = AppSettings.getInstance();
first.setTheme("dark");
System.out.println(first == second);
System.out.println(second.getTheme());
Notice notice = NoticeFactory.create("email");
System.out.println(notice.render("Meeting at 16:00"));
ScoreBoard board = new ScoreBoard();
TextDisplay display = new TextDisplay();
HistoryLog history = new HistoryLog();
board.subscribe(display);
board.subscribe(history);
board.setScore(3);
board.unsubscribe(history);
board.setScore(5);
System.out.println(history.getEntries());
}
}
The output is true, dark, Email: Meeting at 16:00, Display: 3, Display: 5 and [3], each on its own line. Java == checks reference identity for these objects. The notice factory returns the interface type, and the score publisher stores ScoreObserver references.
This program is single-threaded. The eager singleton construction uses Java class initialization, while the mutable theme and observer lists still need additional coordination if a later version introduces concurrent access.
21 | ADD A NEW OBSERVER WITHOUT EDITING THE SUBJECT
class TeacherDashboard:
def __init__(self):
self.latest_score = None
def update(self, score):
self.latest_score = score
board = ScoreBoard()
dashboard = TeacherDashboard()
board.subscribe(dashboard)
board.set_score(7)
print(dashboard.latest_score)
# 7
ScoreBoard does not need a new teacher-specific branch. It already knows how to call update on subscribers. The new object joins through the existing contract, which supports extension and reuse.
This is loose coupling relative to naming every concrete destination inside ScoreBoard, not an absence of dependencies. The subject still depends on update behaving as agreed, and synchronous callbacks still affect timing and error handling.
22 | OBSERVER LIFETIME AND EVENT RULES
Our publisher holds strong references to subscribed observers. If a screen closes but remains subscribed, the publisher can keep its object reachable and continue sending updates. Unsubscribe when the observer no longer needs notifications, and decide who is responsible for doing so.
For more complex systems, specify notification order, callback failures, repeated events and callbacks that trigger further state changes. A callback that changes the score again can create confusing nested notifications or even a loop. The small example avoids that behaviour by contract.
Observer is also different from automatically guaranteeing reliable remote delivery. Notifications here are direct in-process method calls. Network messaging, retries and durable event storage introduce additional responsibilities.
23 | HOW THE PATTERNS USE EARLIER OOP IDEAS
| Earlier idea | Role in these examples |
|---|---|
| Abstraction | Notice and ScoreObserver expose useful common operations |
| Polymorphism | Different products render differently; different observers implement update differently |
| Encapsulation | Creation state and subscription lists are managed through defined operations |
| Object relationships | The score publisher refers to independently created observers |
| Modularity | Creation, rendering, state changes and reactions have focused responsibilities |
A factory does not replace polymorphism: it can supply the object that the caller then uses polymorphically. Observer similarly relies on a common callback operation but adds registration and notification behaviour.
A publisher holding observer references does not own the observers’ entire lifetime in this example. They are created separately and remain accessible after unsubscribe. Use the ownership reasoning from the previous lesson when explaining this relationship.
24 | TEST EACH PATTERN’S PROMISE
first = AppSettings()
first.set_theme("light")
second = AppSettings()
assert first is second
first.set_theme("dark")
assert second.theme == "dark"
first.set_theme("light") # Restore shared state for later tests.
assert isinstance(create_notice("email"), EmailNotice)
assert create_notice("screen").render("Hello") == "Screen: Hello"
board = ScoreBoard()
history = HistoryLog()
board.subscribe(history)
board.subscribe(history)
assert board.set_score(2) is True
assert history.entries == [2]
assert board.set_score(2) is False
board.unsubscribe(history)
board.set_score(4)
assert history.entries == [2]
Run these tests with all three Python pattern definitions available. Singleton tests check identity and restore shared state. Factory tests check product selection and compatible behaviour. Observer tests check duplicate subscription, change notifications and unsubscribe.
Also test unknown factory kinds and invalid scores. A useful test should check the pattern’s intended effect, not merely that the class names contain words such as Factory or Observer.
25 | CHOOSE A PATTERN FROM THE REQUIREMENT
| Scenario | Reasonable choice | Reason or caution |
|---|---|---|
| One coordinator shared within a controlled runtime | Singleton may fit | Confirm uniqueness is required; consider injecting one ordinary instance |
| Several product types selected from a channel value | Factory | Concentrate creation choices and return a common product contract |
| Display, log and dashboard react to a score change | Observer | Register compatible listeners without hard-coding every reaction |
| One short calculation with no variation | An ordinary function may be enough | Extra pattern classes can add unnecessary complexity |
| One shared value across several web-server processes | A local singleton is insufficient | Use an appropriate shared service or storage design |
Patterns trade one kind of complexity for a structure intended to manage recurring variation. Explain the benefit in the scenario and acknowledge the cost. Naming the pattern without identifying the problem does not justify the choice.
26 | EXPLAIN THE MECHANISM AND THE BENEFIT
For singleton: the creation route returns the existing settings instance, so screens obtain shared state through a controlled access point. For factory: object selection is kept behind a creation operation, so the caller can use a common interface without choosing concrete constructors itself.
For observer: the publisher records subscribers and calls their common update operation after a change. Therefore a new compatible reaction can be added by subscribing another object rather than rewriting the score-update logic.
Your challenge is to extend the quiz app with an AppNotice factory product and an AchievementObserver that records when a score first reaches 10. Subscribe it, test scores 4, 10 and 12, then unsubscribe it. Explain which pattern solves creation and which solves change notification. You have reached the end of B3; continue to the revision page.