B3.2.5 Design patterns
HL onlyCommand term: Explain1. Singleton: one catalogue for everyone
The front desk and the phone app both need the library catalogue. Step through with and without the singleton pattern, and see what happens when the desk adds a book.
2. Factory: one place that decides which class to create
Rows arrive from a file as text. The client code never names Book, DVD or Ebook: it hands each row to the factory, which chooses the right subclass. Choose a row or type your own (kind,title,extra).
3. Observer: tell everyone who is waiting
The book Dune is on loan. Members and other parts of the system can subscribe to it. When it is returned, the book notifies every subscriber; it does not need to know what each one does with the news.
4. Flip-card deck
Click to flip. Say the answer before you flip.
5. Which pattern fits?
Match each problem to the design pattern that solves it. Streaks of 3+ score double.
6. 45-second speed round: count them
How many objects are created (singleton), or how many notifications are sent (observer)? A wrong answer costs 3 seconds.
| Pattern | Problem in ShelfWise | Class |
|---|
Expected output
Until the TODOs are done, the tests stop with an error at the first Catalogue.get().
Think about it
- Why does Ana receive two messages but Ben only one?
- To add Ebooks, which class must change, and which classes stay exactly as they are?
Catalogue.get()behaves like a global variable. What problems could that cause in testing?- The book calls
notify(self)on each watcher without knowing whether it is a Member, a display board or a logger. Which OOP principle makes that possible?
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Singleton settings
ShelfWise must have exactly one settings object. Write a class Settings using the Singleton pattern: Settings.instance() always returns the same object. Show that a change made through one reference is seen through another.
Starter file (write your code where it says pass # your code here):
class Settings:
pass # your code here
# ---- tests ----
a = Settings.instance()
b = Settings.instance()
a.max_loans = 5
print(b.max_loans, a is b)
Expected output when your code is correct:
5 True
Hint
Model solution
class Settings:
_instance = None
def __init__(self):
self.max_loans = 3
self.theme = "sketch"
@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
# ---- tests ----
a = Settings.instance()
b = Settings.instance()
a.max_loans = 5
print(b.max_loans, a is b)
Task 2: A factory for library items
ShelfWise lends books, DVDs and laptops, each with a different loan period (14, 7 and 1 days) and daily fine (0.2, 1 and 10 yuan). Write a class per item type and a Factory function make_item(kind, title) that returns the right object, raising ValueError for an unknown kind. Code that uses items should only call make_item, never the classes directly.
Starter file (write your code where it says pass # your code here):
class Item:
pass # your code here
class Book(Item):
pass # your code here
class DVD(Item):
pass # your code here
class Laptop(Item):
pass # your code here
def make_item(kind, title):
pass # your code here
# ---- tests ----
items = [make_item(k, t) for k, t in [("book", "Dune"), ("dvd", "Hero"), ("laptop", "LT-07")]]
print(items)
print([i.fine_for(3) for i in items])
try:
make_item("bike", "B1")
except ValueError as e:
print("ValueError:", e)
Expected output when your code is correct:
[Book('Dune', 14 days), DVD('Hero', 7 days), Laptop('LT-07', 1 days)]
[0.6, 3, 30]
ValueError: unknown item kind: bike
Hint
Model solution
class Item:
days, fine = 0, 0
def __init__(self, title):
self.title = title
def fine_for(self, days_late):
return round(max(0, days_late) * self.fine, 2)
def __repr__(self):
return f"{type(self).__name__}({self.title!r}, {self.days} days)"
class Book(Item):
days, fine = 14, 0.2
class DVD(Item):
days, fine = 7, 1
class Laptop(Item):
days, fine = 1, 10
def make_item(kind, title):
kinds = {"book": Book, "dvd": DVD, "laptop": Laptop}
if kind not in kinds:
raise ValueError(f"unknown item kind: {kind}")
return kinds[kind](title)
# ---- tests ----
items = [make_item(k, t) for k, t in [("book", "Dune"), ("dvd", "Hero"), ("laptop", "LT-07")]]
print(items)
print([i.fine_for(3) for i in items])
try:
make_item("bike", "B1")
except ValueError as e:
print("ValueError:", e)
Task 3: Observer: reservation alerts
When a reserved book is returned, every student waiting for it must be told. Implement the Observer pattern: Book (the subject) has subscribe(observer), unsubscribe(observer) and returned(), which calls notify(book) on every observer. Write two observer classes: Student (stores messages) and Librarian (counts notifications). Explain how this design reduces coupling.
Starter file (write your code where it says pass # your code here):
class Book:
pass # your code here
class Student:
pass # your code here
class Librarian:
pass # your code here
# ---- tests ----
dune = Book("Dune")
ana, ben, desk = Student("Ana"), Student("Ben"), Librarian()
for o in (ana, ben, desk):
dune.subscribe(o)
dune.returned()
dune.unsubscribe(ana)
dune.returned()
print(ana.inbox, ben.inbox, desk.count)
Expected output when your code is correct:
['Dune is back'] ['Dune is back', 'Dune is back'] 2
Hint
Model solution
The Book only knows that its observers have a notify method; it does not know whether they are students, librarians or a future app. New observer types can be added without changing Book, so the classes are loosely coupled.
class Book:
def __init__(self, title):
self.title = title
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)
def returned(self):
for o in list(self._observers):
o.notify(self)
class Student:
def __init__(self, name):
self.name = name
self.inbox = []
def notify(self, book):
self.inbox.append(f"{book.title} is back")
class Librarian:
def __init__(self):
self.count = 0
def notify(self, book):
self.count += 1
# ---- tests ----
dune = Book("Dune")
ana, ben, desk = Student("Ana"), Student("Ben"), Librarian()
for o in (ana, ben, desk):
dune.subscribe(o)
dune.returned()
dune.unsubscribe(ana)
dune.returned()
print(ana.inbox, ben.inbox, desk.count)
Learning objectives
By the end of this page you should be able to:
- Explain what a design pattern is and why reusable solutions to recurring problems are valuable.
- Explain the singleton pattern and construct a class that guarantees a single instance with a global point of access.
- Explain the factory pattern and construct a factory that creates objects of different subclasses without the client naming them.
- Explain the observer pattern and construct a subject that notifies registered observers when its state changes.
- Select an appropriate pattern for a scenario and discuss its advantages and drawbacks.
What is a design pattern?
A design pattern is a general, reusable solution to a problem that keeps recurring in software design. It is not finished code but a proven template for arranging classes and objects, with a name that lets developers communicate quickly ("use an observer here"). Patterns build directly on encapsulation, inheritance, polymorphism and composition.
Singleton (creational)
Problem: exactly one object of a class must exist, and many parts of the program need it (a configuration, a log, a database connection, the catalogue). Solution: the class controls its own creation: it stores its single instance in a static (class) variable and hands out that same object every time.
class Catalogue:
_instance = None # class variable holds the only object
@classmethod
def get_instance(cls):
if cls._instance is None: # create it only the first time
cls._instance = cls()
return cls._instance
// Java: a private constructor stops anyone else using new
public class Catalogue {
private static Catalogue instance;
private Catalogue() { }
public static Catalogue getInstance() {
if (instance == null) instance = new Catalogue();
return instance;
}
}
+ one consistent shared object; created only when first needed. − acts like a global variable, hides dependencies, and makes testing harder; needs care with multiple threads.
Factory (creational)
Problem: code needs to create objects, but which subclass depends on data known only at run time, and you do not want if kind == ... scattered everywhere. Solution: one factory method decides and returns the object through a common superclass type.
class ItemFactory:
@staticmethod
def create(kind, title, extra):
if kind == "book":
return Book(title, extra)
if kind == "dvd":
return DVD(title, extra)
raise ValueError("unknown item type: " + kind)
item = ItemFactory.create("dvd", "Up", 96) # the client never names DVD
+ creation logic in one place; clients depend only on the superclass; adding a type changes only the factory. − an extra class; the factory itself must be updated for each new type.
Observer (behavioural)
Problem: when one object changes, several others must react, but the changing object should not be hard-wired to them. Solution: the subject keeps a list of observers; they subscribe and unsubscribe at run time; on a change, the subject calls each observer's update (notify) method.
class Book: # the subject
def __init__(self, title):
self.title = title
self._watchers = []
def watch(self, observer):
self._watchers.append(observer)
def unwatch(self, observer):
self._watchers.remove(observer)
def give_back(self):
for w in self._watchers: # polymorphism: any object with notify()
w.notify(self)
+ loose coupling; any number of observers added or removed at run time; used in user interfaces (button clicks), notifications and spreadsheets. − the order of notification is not obvious; forgotten subscriptions can cause unexpected updates or memory leaks.
Choosing a pattern
| Pattern | Type | Use it when | Builds on |
|---|---|---|---|
| Singleton | creational | exactly one shared instance is needed | static members, private constructor |
| Factory | creational | the class to create is decided at run time | inheritance, polymorphism, abstraction |
| Observer | behavioural | many objects must react to changes in one object | polymorphism, aggregation, loose coupling |
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Define the term design pattern. [2]
2. Explain how the singleton pattern ensures that only one instance of a class exists. [3]
3. A drawing program reads shape names ("circle", "square") from a file. Construct a factory that returns the correct Shape subclass, and explain one benefit of this design. [4]
class ShapeFactory:
@staticmethod
def create(name, size):
if name == "circle":
return Circle(size)
if name == "square":
return Square(size)
raise ValueError("unknown shape")4. A weather station's temperature reading is shown on a phone app, a web page and a wall display. Outline how the observer pattern could be applied. [4]
5. Identify the most suitable pattern for each: (a) a program-wide log file writer; (b) creating different enemy types from a level file; (c) updating a score display whenever the player's score changes. [3]
6. Discuss one disadvantage of the singleton pattern. [2]