B3.2.5 · Fundamentals of OOP for multiple classes (HL)
B3.2.5 · 多个类的 OOP 基础(HL)
Design patterns in OOP
OOP 中的设计模式
Three problems that come up in almost every large program, and the shapes programmers have agreed on for solving them.
几乎每个大型程序都会遇到的三个问题,以及程序员们公认的解决它们的形态。
Explainer
讲解
Calderbrook Interchange is building the software behind its departure boards. Three problems come up almost immediately, and none of them is really about buses. There must be exactly one departure log, however many parts of the system want to write to it. Alerts come in several kinds, and the code raising one should not have to know which class to build. And when a service is delayed, several very different displays all need telling at once, without the service knowing what a display even is.
Calderbrook 换乘枢纽正在为它的发车显示屏开发软件。几乎一开始就出现了三个问题,而它们没有一个真正与公交车有关。无论系统中有多少部分想写入发车日志,都只能有一份。警报有好几种,而发出警报的代码不应该需要知道要创建哪个类。当一班车晚点时,好几种截然不同的显示屏都需要同时被告知,而这班车却不知道显示屏到底是什么。
A design pattern is a named, reusable solution to a problem that keeps recurring across different programs. It is not code you copy, it is a shape you apply: a description of which classes exist, what each is responsible for, and how they talk to each other.
设计模式(design pattern)是针对在不同程序中不断重复出现的问题,给出的一个有名字、可复用的解决方案。它不是你可以复制的代码,而是你要应用的一种形态:描述有哪些类、每个类负责什么,以及它们如何相互沟通。
Two benefits are worth naming in an answer. Patterns are proven, so you inherit a solution whose weaknesses are already understood rather than inventing one. And they are named, which gives developers shared vocabulary: saying "make it a singleton" communicates an entire design in three words.
在答案中值得说出两点好处。模式是久经验证的,所以你继承的是一个弱点已被充分了解的解决方案,而不是自己发明一个。而且它们是有名字的,这给开发者提供了共同的词汇:说一句"把它做成单例",三个字就传达了整个设计。
The three below are the ones the syllabus asks for. Each is introduced by the recurring problem it exists to answer, because that problem is what the second elaboration bullet is really asking about.
下面这三种是考纲要求掌握的。每一种都从它要回答的反复出现的问题引入,因为第二条拓展要点真正问的正是这个问题。
Pattern 1
模式 1
Singleton
单例(Singleton)
Something in the system must exist exactly once. If two copies are created by accident, they drift apart and neither is right. At Calderbrook the departure log is like this: two logs would mean two different answers to "what happened this morning?"
系统中的某样东西必须恰好存在一份。如果意外创建了两份,它们就会各行其是,没有一份是对的。在 Calderbrook,发车日志就是这样:两份日志就意味着对"今天早上发生了什么?"有两个不同的答案。
Under the singleton pattern, a class is written so that it can never be instantiated twice: the first request creates the object, every later request receives that same one, and the class exposes a single agreed route to it. The class itself takes responsibility for preventing a second instance, rather than trusting every caller to remember.
在单例模式下,一个类被写成永远不能被实例化两次:第一次请求创建对象,之后的每次请求得到的都是同一个对象,而且这个类对外只暴露一条约定好的访问途径。由类本身负责阻止第二个实例,而不是相信每个调用者都会记得。
class DepartureLog: _instance = None # the one instance lives on the CLASS def __init__(self): self.entries = [] @staticmethod def get(): # the single agreed way in if DepartureLog._instance == None: DepartureLog._instance = DepartureLog() return DepartureLog._instance def record(self, text): self.entries.append(text) # every caller gets the SAME object, so every entry lands in one place DepartureLog.get().record("Service 12 delayed") DepartureLog.get().record("Service 4 cancelled")
The give-away is a class variable holding an instance of its own class, plus a method that hands it out. Note that get() is a static method: it has to work before any instance exists, so it cannot need one.
特征是一个保存自己所属类的实例的类变量,加上一个把它交出去的方法。注意 get() 是一个静态方法:它必须在任何实例存在之前就能工作,所以不能依赖实例。
Pattern 2
模式 2
Factory
工厂(Factory)
Several related classes exist, and the code that needs one should not have to choose between them. At Calderbrook a delay, a cancellation and a platform change are three different alert classes, but the code reporting an incident only knows a string from an operator's form.
存在几个相关的类,而需要其中一个的代码不应该需要在它们之间做选择。在 Calderbrook,晚点、取消和站台变更是三个不同的警报类,但报告事故的代码只知道操作员表单里的一个字符串。
The factory pattern puts object creation behind a single method that decides which class to instantiate and returns it. The caller asks for what it wants by description and receives a ready-made object, without naming any concrete class itself.
工厂模式把对象的创建放在一个方法后面,由它决定实例化哪个类并返回。调用者通过描述来请求自己想要的东西,得到一个现成的对象,而自己不必点出任何具体的类。
class AlertFactory: @staticmethod def create(kind, detail): # ONE entry point for three classes if kind == "delay": return DelayAlert(detail) elif kind == "cancelled": return CancellationAlert() elif kind == "platform": return PlatformChangeAlert(detail) return None # the caller never writes DelayAlert(...) or CancellationAlert() alert = AlertFactory.create("delay", 7) print(alert.text())
Every alert class offers a text() method, so whatever comes back can be used the same way. That shared interface is what makes the factory safe, and it is abstraction and polymorphism doing the work underneath.
每个警报类都提供一个 text() 方法,所以不管返回的是哪一个,使用方式都一样。这个共同的接口正是工厂之所以安全的原因,而它底层起作用的是抽象和多态。
A constructor builds one known class, and the caller has to name it. A factory decides which class to build. Adding a fourth alert type means editing the factory only, while every place that reports an incident keeps working untouched.
构造方法构建一个已知的类,调用者必须指名道姓。工厂则决定要构建哪个类。新增第四种警报类型,只需要修改工厂,而每一个报告事故的地方都照常工作,不用动。
Pattern 3
模式 3
Observer
观察者(Observer)
When one object changes, an unknown number of others need to react, and the changing object should not have to know who they are. At Calderbrook a delayed service must reach the platform screen, the mobile app and the announcement system, and next year something else nobody has built yet.
一个对象发生变化时,数量未知的其他对象需要作出反应,而发生变化的对象不应该需要知道它们是谁。在 Calderbrook,一班晚点的车必须通知站台屏幕、手机应用和广播系统,明年还要通知某个目前没人做出来的东西。
The observer pattern lets one object (the subject) keep a list of dependent objects (the observers) and notify every one of them automatically when its state changes. Observers subscribe and unsubscribe at run time, and the subject knows nothing about them beyond the fact that they can be notified.
观察者模式让一个对象(主题,subject)保存一个依赖对象(观察者,observers)的列表,并在自身状态变化时自动通知其中的每一个。观察者可以在运行时订阅和取消订阅,而主题除了知道它们可以被通知之外,对它们一无所知。
class BusService: # the SUBJECT def __init__(self, code): self.code = code self.observers = [] # who wants telling def subscribe(self, observer): self.observers.append(observer) def unsubscribe(self, observer): self.observers.remove(observer) def announce(self, message): # tell everyone, whoever they are for o in self.observers: o.update(self.code, message) s12 = BusService("Service 12") s12.subscribe(PlatformScreen("Platform 3")) # an OBSERVER s12.subscribe(MobileApp("Calderbrook app")) # another one s12.announce("delayed by 7 minutes")
Notice what BusService does not contain: no mention of screens, apps or announcements. It only requires that anything on its list has an update() method. That is what lets a new display type be added years later without touching this class at all.
注意 BusService 里没有什么:没有提到屏幕、应用或广播。它只要求列表上的任何东西都有一个 update() 方法。这就使得几年后新增一种显示类型时,完全不用改动这个类。
Explainer
讲解
Recognising each one
如何辨认每一种
An exam question usually gives you a situation and asks which pattern fits. Match on the problem, not on the vocabulary.
考试题通常会给你一个情境,问哪种模式适用。要根据问题来匹配,而不是根据词汇。
| Pattern | 模式 | The recurring challenge it solves | 它解决的反复出现的难题 | What to look for in code | 在代码中要找什么 |
|---|---|---|---|---|---|
| Singleton | 单例 | Exactly one of something must exist, and everything must share it | 某样东西必须恰好存在一份,而且大家必须共用它 | A class variable holding an instance of its own class, reached through a static method such as get() | 一个保存自己所属类的实例的类变量,通过 get() 之类的静态方法访问 |
| Factory | 工厂 | Choosing between several related classes, without the caller naming any of them | 在几个相关的类之间做选择,而调用者不点出其中任何一个 | One method that returns different classes depending on its argument | 一个方法,根据参数返回不同的类 |
| Observer | 观察者 | One change must reach many objects, and their number is not known in advance | 一次变化必须传达给许多对象,而且它们的数量事先未知 | A list of subscribers, a subscribe method, and a loop that calls the same method on each | 一个订阅者列表、一个订阅方法,以及对每个订阅者调用同一个方法的循环 |
Each one removes a dependency. The caller stops depending on when an object was created, or on which class it is, or on who needs telling. That is why patterns make a system easier to extend: the parts know less about each other than they otherwise would.
每一种都消除了一种依赖。调用者不再依赖对象是何时创建的、是哪个类,或者谁需要被通知。这就是模式让系统更容易扩展的原因:各个部分彼此了解得比原本更少。
Try it yourself
动手试试
All three, in one departure board
三者合一:一块发车显示屏
The Calderbrook system, live and editable. Worth trying: add a third observer class and subscribe it without touching BusService, and check the singleton really is one object by recording through one handle and reading through another.
Calderbrook 的系统,可在线编辑运行。值得尝试:添加第三个观察者类并订阅它,而不改动 BusService;并且通过一个句柄记录、另一个句柄读取,来检验单例确实是同一个对象。
Running in offline fallback mode. The full Python engine couldn’t load (blocked school network, or no internet), so this console switched automatically to a small hand-written engine. It runs this page’s scenario, including static methods, list subscription and object factories, but it isn’t full Python.
正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括静态方法、列表订阅和对象工厂,但它不是完整的 Python。
Check your understanding
检查你的理解
A weather app must alert an unknown number of widgets whenever a new reading arrives, and new widget types are added regularly without changing the reading code. Which pattern fits, and why?
一个天气应用在每次有新读数到达时,必须提醒数量未知的小部件,而且新的小部件类型会定期增加,读数代码却不用修改。哪种模式适用,为什么?
Common mistake
常见错误
B3.2.5B3.2.5 的这一常见模式RecurringCandidates describe the mechanism of a pattern accurately and never say which problem it solves. "A factory has a method that creates objects" is true of every constructor ever written, so on its own it earns little. The mark is in the purpose: the caller does not have to know which class it is getting.
反复出现考生准确地描述了一种模式的机制,却从不说它解决什么问题。"工厂有一个创建对象的方法"对所有写过的构造方法都成立,所以单凭这句话几乎得不到分。分数在于目的:调用者不必知道自己拿到的是哪个类。
The second error is treating singleton as a synonym for "a class with static methods". A class of static methods holds no state and is never instantiated; a singleton is a real object with real attributes, of which exactly one exists.
第二个错误是把单例当作"带静态方法的类"的同义词。一个全是静态方法的类不保存状态,也从不被实例化;而单例是一个带有真实属性的真实对象,而且恰好只存在一个。
Answer frame that scores: name the recurring problem → name the pattern → say what the pattern removes the need for the rest of the program to know.
能得分的答题框架:指出反复出现的问题 → 指出模式 → 说明这种模式让程序的其余部分不再需要知道什么。
What a weak answer looks like: “The observer pattern is when objects observe another object and get updated.” This restates the name without naming a problem, and would fit almost any event-driven code.
较弱的答案是这样的:“观察者模式就是对象观察另一个对象并获得更新。”这只是把名字重述了一遍,没有指出任何问题,而且几乎适用于任何事件驱动的代码。
What it should say: “When a service is delayed, several displays must react, but the number and type of displays change over time. The observer pattern lets each display subscribe to the service, so the service notifies its list without knowing what any of them are, and a new display type can be added without editing BusService.” Problem, pattern, and what it removes.
应该这样写:“当一班车晚点时,好几个显示屏必须作出反应,但显示屏的数量和类型会随时间变化。观察者模式让每个显示屏订阅这个服务,所以服务通知它的列表时不需要知道它们是什么,新增一种显示类型也不用编辑 BusService。”问题、模式,以及它消除了什么。
Linking question
联系性问题
How this connects to the rest of the syllabus
这与考纲其余部分如何联系
The IB syllabus is deliberately woven together, not a stack of isolated topics. Here's how design patterns connect specifically to A4 (machine learning).
IB 考纲是刻意编织在一起的,而不是一堆孤立的主题。下面是设计模式与 A4(机器学习)的具体联系。
How can design patterns in OOP facilitate the architecture of scalable and maintainable machine learning models? (All three patterns on this page appear in real ML systems: a single shared model registry so every request scores against the same loaded weights, a factory that returns whichever model version a request asks for without the caller naming it, and observers that react when training finishes, one logging metrics, another retiring the previous model.)
OOP 中的设计模式如何促进可扩展且可维护的机器学习模型的架构?(本页的三种模式都出现在真实的机器学习系统中:一个单一的共享模型注册表,使每个请求都用同一份已加载的权重打分;一个工厂,根据请求返回它所要的任何模型版本,而调用者不必点出名字;以及在训练结束时作出反应的观察者,一个记录指标,另一个让上一个模型退役。)
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[3]Explain why DepartureLog is implemented as a singleton, referring to what would go wrong without it.
[3]解释为什么 DepartureLog 被实现为单例,并说明没有它会出什么问题。
Marking points
评分要点
- DepartureLog must be the single shared record of departures for the whole system.
- The singleton pattern ensures only one instance is ever created, with one global access point.
- Without it, different parts of the system could each make their own DepartureLog, so recorded departures would be split across separate objects and no single log would be complete or consistent.
- DepartureLog 必须是整个系统唯一的、共享的发车记录。
- 单例模式确保只创建一个实例,并有一个全局访问点。
- 没有它,系统的不同部分可能各自创建自己的 DepartureLog,于是记录的发车会分散在多个独立对象中,没有一份日志是完整或一致的。
[4]Calderbrook adds a DiversionAlert. Construct the change needed, and state which parts of the existing system must be edited and which must not.
[4]Calderbrook 新增了一个 DiversionAlert。构建所需要的改动,并说明现有系统的哪些部分必须编辑,哪些不能编辑。
Marking points
评分要点
- Create a DiversionAlert class with an update() method, matching the interface every observer already has.
- Register a DiversionAlert instance with the BusService (subject) by adding it to the observer list.
- Must be edited: the code that constructs and registers observers, to add the new one.
- Must not be edited: BusService itself, the other alert classes, and the notify logic, because the subject calls update() on every observer without knowing their types.
- 创建一个带 update() 方法的 DiversionAlert 类,匹配每个观察者已有的接口。
- 通过把一个 DiversionAlert 实例加入观察者列表,把它注册到 BusService(主体)。
- 必须修改:构造并注册观察者的代码,以添加新的那个。
- 不得修改:BusService 本身、其他警报类以及通知逻辑,因为主体在不知道观察者类型的情况下对每个观察者调用 update()。
[5]A developer proposes that BusService should call each display directly instead of keeping a list of observers. Evaluate this proposal.
[5]一位开发者建议 BusService 应该直接调用每个显示屏,而不是保存一个观察者列表。评价这个提议。
Marking points
评分要点
- Calling each display directly means BusService must name every display type in its own code.
- Adding a new display would then require editing BusService, which breaks the open-closed principle.
- It also couples BusService to concrete classes it should not need to know about, making it harder to test and reuse.
- The observer list lets BusService notify any number of observers of any type through a common update() method, with no change when observers are added or removed.
- Evaluation: reject the proposal; the observer list is the better design.
- 直接调用每个显示器意味着 BusService 必须在自己的代码中指名每一种显示类型。
- 那么添加一个新显示器就需要修改 BusService,这违反开闭原则。
- 它还把 BusService 与它本不需要知道的具体类耦合,使其更难测试和复用。
- 观察者列表让 BusService 通过一个共同的 update() 方法通知任意数量、任意类型的观察者,在添加或移除观察者时无需改动。
- 评价:拒绝该提案;观察者列表是更好的设计。
Flashcards
闪卡
Active recall for this statement’s key terms.
针对本条陈述关键术语的主动回忆。
Keep this statement’s practice with you
把本条陈述的练习带在身边
Free account: unlock every revision question and flashcard for B3.2.5, and every other IB CS 2027 statement.
免费账号:解锁 B3.2.5 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。