How unit 3 is examined
This unit covers the idea of a design pattern, the GoF catalogue and the creational patterns (Singleton, Factory Method, Abstract Factory, Builder, Prototype); no question on it appeared in the supplied papers, so every part is taught for the first time it is asked.
Design patterns - 1
Not asked since 2022
Definition. A design pattern is a proven, reusable solution to a commonly occurring problem in software design, described as a template that can be adapted to many situations rather than as finished code.
Key points.
- A pattern is written down with a name, the problem it solves, the solution (classes and their collaboration) and the consequences of using it, so that developers share one vocabulary.
- The Gang of Four (Gamma, Helm, Johnson, Vlissides) catalogued 23 patterns in the book "Design Patterns: Elements of Reusable Object-Oriented Software", which is why they are called GoF patterns.
- The 23 patterns fall into three groups: creational (how objects are created), structural (how classes and objects are composed) and behavioural (how objects communicate and share responsibility).
- Patterns follow the principle "program to an interface, not an implementation" and prefer object composition over class inheritance, which keeps code loosely coupled and easy to change.
- Patterns improve reuse, maintainability and communication in a team, but a pattern used where a plain solution would do only adds needless complexity.
Diagram.
Creational patterns. Creational patterns hide how objects are made, so the system does not depend on how its objects are created, composed and represented.
| Pattern | Intent | Typical use |
|---|---|---|
| Singleton | Only one instance of a class, with a global access point | Logger, configuration, database connection pool |
| Factory Method | An interface for creating an object, but subclasses decide which class to instantiate | Document creators, UI widgets per platform |
| Abstract Factory | An interface for creating families of related objects without naming concrete classes | Look-and-feel toolkits (Windows, Mac widgets) |
| Builder | Separates construction of a complex object from its representation, built step by step | Building a meal, a report, an SQL query |
| Prototype | Creates new objects by cloning an existing prototype | Copying costly-to-create objects |
Singleton.
- The constructor is made private (or controlled) so no other class can create instances with
new. - The class keeps one static reference to its only instance.
- A static method such as
getInstance()creates the instance on first call and returns the same one afterwards. - In multi-threaded programs the creation must be synchronised, or the instance created eagerly at class-load time.
class Single:
_i = None
def __new__(c):
if c._i is None:
c._i = super().__new__(c)
return c._i
print(Single() is Single()) # True
Factory Method.
- A
Creatordeclares the factory method that returns aProductinterface. - Each
ConcreteCreatoroverrides it to return aConcreteProduct. - The client works only with the
Productinterface, so a new product is added without changing client code, which follows the open-closed principle.
class Dog:
def speak(s): return "Woof"
class Cat:
def speak(s): return "Meow"
def make(kind):
return {"dog": Dog, "cat": Cat}[kind]()
print(make("cat").speak()) # Meow
Abstract Factory.
- An
AbstractFactoryinterface declares one creation method for each product in a family (for examplecreateButton()andcreateCheckbox()). - Each
ConcreteFactory(for example WindowsFactory, MacFactory) creates the products of one consistent family. - The client uses only the abstract factory and abstract products, so the whole family can be switched by changing one factory object.
- It differs from Factory Method because it creates several related products, usually with composition, instead of a single product through inheritance.
Builder.
- A
Directorcontrols the order of construction steps and calls theBuilderinterface. - A
ConcreteBuilderimplements the steps (buildPartA(),buildPartB()) and returns the finished product throughgetResult(). - The same construction process can therefore produce different representations, and it avoids a constructor with many parameters.
Prototype.
- A
Prototypeinterface declares aclone()operation and the concrete class copies itself. - The client obtains new objects by cloning a registered prototype instead of building one from scratch, which saves cost when creation is expensive.
- A shallow copy shares nested objects with the original, whereas a deep copy duplicates them; a deep copy is needed for independent objects.
import copy
class P:
def __init__(s): s.tags = ["a"]
a = P()
b = copy.deepcopy(a)
b.tags.append("b")
print(a.tags, b.tags) # ['a'] ['a', 'b']
Answer frame. Open with the definition of a design pattern and its three GoF groups; draw the classification tree; then develop the creational patterns in the order Singleton, Factory Method, Abstract Factory, Builder, Prototype, giving intent, structure and one example each; close with the benefit of reuse and loose coupling.
Answer frame (one pattern). Open with the intent of the pattern in one line; draw its class diagram (for Singleton a single class with a private constructor and getInstance()); list the participants and steps; give a short code snippet and a real use such as a logger; close with one advantage and one drawback.
Comparison.
| Basis | Factory Method | Abstract Factory |
|---|---|---|
| Creates | One product | A family of related products |
| Mechanism | Inheritance, subclass overrides the method | Composition, a factory object is passed in |
| Interface | One creation method | One creation method per product |
| Adding a new product kind | Add a subclass | Change the factory interface, which is harder |
| Adding a new family | Not directly supported | Add a new concrete factory |
Pitfall: Do not say Singleton is a structural pattern or that Prototype uses
new; Singleton, Factory, Abstract Factory, Builder and Prototype are all creational, and Prototype creates objects by cloning.
Last-minute revision
- A design pattern is a proven, reusable solution to a recurring design problem, given as a template.
- GoF gave 23 patterns: creational, structural and behavioural.
- Creational patterns: Singleton, Factory Method, Abstract Factory, Builder, Prototype.
- Singleton means one instance, a private constructor and a static
getInstance(). - Factory Method lets subclasses decide which class to instantiate.
- Abstract Factory creates families of related objects through concrete factories.
- Builder constructs a complex object step by step using a Director and a Builder.
- Prototype creates new objects by cloning; deep copy duplicates nested objects.
- Design principle: program to an interface and prefer composition over inheritance.
- Factory Method uses inheritance; Abstract Factory uses composition.
Memory hooks
- GoF = 23 patterns in 3 groups: Create, Structure, Behave.
- Creational five: "S-F-A-B-P" = Single, Factory, Abstract, Builder, Prototype.
- Singleton = "only one".
- Factory = "ask the factory, do not call new".
- Builder = "step by step, Director in charge".
- Prototype = "photocopy, not rebuild".
Coverage checklist
- Design patterns - 1: definition, GoF classification, creational patterns Singleton, Factory Method, Abstract Factory, Builder, Prototype, comparison of Factory Method and Abstract Factory (no past questions in the supplied papers).