Home › Theme B › B3 › B3.2 › B3.2.5

B3.2.5 Design patterns

HL onlyCommand term: Explain

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

Version:

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

Row

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.

Round 0/10Score 0Streak 0Best 0
Press start!

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.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 7, task 5 (HL), the final task. Bring three patterns together: one shared Catalogue for the whole program (singleton), an ItemFactory that turns raw rows into the right kind of item (factory), and items that notify waiting members when they are returned (observer).
PatternProblem in ShelfWiseClass

Expected output

Until the TODOs are done, the tests stop with an error at the first Catalogue.get().

Skipped: unknown item type: comic 2 True ['Dune is available', 'Dune is available'] ['Dune is available'] ['Dune by Herbert', 'Up (96 min)']

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

    ShelfWise is complete. From variables and lists (B2) to a family of encapsulated, polymorphic classes using composition and design patterns (B3). Next: B4 abstract data types (HL).

    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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

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

    File: b3_2_5_average.py
    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
    Store the single object in a class variable and create it only the first time.
    Model solution
    File: b3_2_5_average_solution.py
    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)
    
    Moderate

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

    File: b3_2_5_moderate.py
    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
    A dictionary from kind names to classes keeps the factory short.
    Model solution
    File: b3_2_5_moderate_solution.py
    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)
    
    Challenging

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

    File: b3_2_5_challenging.py
    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
    The subject keeps a list of observers and calls the same method on each.
    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.

    File: b3_2_5_challenging_solution.py
    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:

    1. Explain what a design pattern is and why reusable solutions to recurring problems are valuable.
    2. Explain the singleton pattern and construct a class that guarantees a single instance with a global point of access.
    3. Explain the factory pattern and construct a factory that creates objects of different subclasses without the client naming them.
    4. Explain the observer pattern and construct a subject that notifies registered observers when its state changes.
    5. 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

    PatternTypeUse it whenBuilds on
    Singletoncreationalexactly one shared instance is neededstatic members, private constructor
    Factorycreationalthe class to create is decided at run timeinheritance, polymorphism, abstraction
    Observerbehaviouralmany objects must react to changes in one objectpolymorphism, 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]

    A general, reusable solution / template [1] for a commonly recurring problem in software design [1].

    2. Explain how the singleton pattern ensures that only one instance of a class exists. [3]

    The constructor is made private (Java) so other classes cannot create objects directly [1]; the class holds its only instance in a static variable [1]; a static method returns that instance, creating it only if it does not yet exist [1].

    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]

    A factory class / static method taking the shape name [1]; returns a Circle or a Square object according to the name [1]; handles an unknown name (error or None) [1]; benefit: the client code only works with the Shape type, so object creation is in one place and new shapes require changing only the factory [1].
    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]

    The weather station is the subject and keeps a list of observers [1]; the app, web page and display are observers with a common update method [1]; they subscribe / register with the station [1]; when the temperature changes, the station calls update on each observer, which refreshes its own display [1].

    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]

    (a) singleton [1]; (b) factory [1]; (c) observer [1].

    6. Discuss one disadvantage of the singleton pattern. [2]

    It provides global state that any part of the program can change [1], so dependencies are hidden and tests can affect each other / it is hard to replace with a test version [1]. (Or: in multi-threaded programs two threads may create two instances unless creation is synchronised.)