B3.2.4 · Fundamentals of OOP for multiple classes (HL)
B3.2.4 · 多个类的 OOP 基础(HL)
Composition and aggregation
组合与聚合
Building a big object out of smaller ones, and deciding whether those smaller ones belong to it or merely work with it.
用较小的对象构建一个大对象,并决定这些较小的对象是属于它,还是只是与它协作。
Explainer
讲解
Alderway Community Radio schedules a programme called Evening Review. The programme is built from segments: a five-minute headline read, a twenty-minute studio interview, each written specifically for that episode. It also has presenters: two members of station staff who are rostered onto it. Both are things the programme "has". But if Evening Review is cancelled tomorrow, its segments are meaningless and should go with it, while its presenters turn up on Monday and host something else.
Alderway 社区电台编排了一个叫 Evening Review 的节目。节目由多个片段组成:一段五分钟的头条播报,一段二十分钟的演播室访谈,每一段都是专门为这一期写的。它还有主持人:两位被排到这个节目上的电台员工。这两样都是节目"拥有"的东西。但如果 Evening Review 明天被取消,它的片段就没有意义了,应该随之消失,而它的主持人周一照常上班,去主持别的节目。
Inheritance builds a class by saying what it is. Composition and aggregation build one by saying what it has: an object holds references to other objects, and delegates work to them, instead of trying to do everything itself.
继承通过说明一个类是什么来构建它。组合和聚合则通过说明它拥有什么来构建:一个对象持有对其他对象的引用,并把工作委托给它们,而不是试图自己做所有事情。
This is what the syllabus means by designing objects from smaller component objects. Programme does not calculate a running time by knowing about minutes; it asks each Segment it holds. The two relationships differ only in who owns the lifetime of the parts.
这就是考纲所说的用较小的组件对象来设计对象。Programme 并不是靠了解分钟数来计算总时长;它是去问自己持有的每一个 Segment。这两种关系只在谁拥有部分的生命周期上有所不同。
You have met these three relationship names before, on B3.1.2, as UML notation. This statement is about what they mean once you are writing the classes themselves.
你在 B3.1.2 中已经以 UML 符号的形式见过这三个关系名称。这条陈述讲的是:当你真正去写这些类时,它们意味着什么。
Explainer
讲解
The two kinds of has-a
两种"拥有"
Composition is a whole-part relationship where the part cannot exist outside its whole. The whole creates its parts, owns them for as long as it lives, and takes them with it when it goes. The two are tightly coupled.
组合(composition)是一种整体与部分的关系,其中部分不能脱离整体而存在。整体创建它的部分,在自己存活期间拥有它们,并在自己消失时一并带走它们。两者是紧耦合的。
Aggregation is a whole-part relationship where the part exists independently. It was created elsewhere, is merely referenced by the whole, can be shared with other wholes at the same time, and carries on existing after the whole is destroyed.
聚合(aggregation)是一种整体与部分的关系,其中部分独立存在。它是在别处创建的,整体只是引用它,可以同时与其他整体共享,并且在整体被销毁之后继续存在。
Ask what should happen to the part when the whole is deleted. If the answer is "it should be deleted too, it means nothing on its own," that is composition. If the answer is "it should carry on, something else may still be using it," that is aggregation.
问一问,当整体被删除时,部分应该怎么样。如果答案是"它也应该被删除,它自己单独没有意义",那就是组合。如果答案是"它应该继续存在,别的东西可能还在使用它",那就是聚合。
Two that are composition
两个组合的例子
A post and its comments
帖子和它的评论
A comment is written onto one particular post and is stored with it. Delete the post and every comment goes with it, because a reply to something that no longer exists means nothing. No other post could ever adopt them.
评论是写在某一个特定帖子上的,并与它存储在一起。删除帖子,每条评论都随之消失,因为对一个已经不存在的东西的回复毫无意义。没有任何别的帖子能够收养它们。
A quiz attempt and its answers
一次测验作答和它的答案
Each answer belongs to one sitting of the quiz. Wipe the attempt and the answers are meaningless: "C" on its own is not information once you no longer know which attempt or question it belonged to.
每个答案属于测验的某一次作答。清除这次作答,答案就失去意义:一旦你不再知道它属于哪次作答或哪道题,单独一个 "C" 并不是信息。
Two that are aggregation
两个聚合的例子
A squad and its players
球队和它的球员
A player existed before joining and carries on after transferring out. The same player object can sit in a club squad and a national squad at the same time, which composition could never allow.
球员在加入之前就已存在,转会离开之后继续存在。同一个球员对象可以同时出现在俱乐部队和国家队中,这是组合绝不允许的。
A basket and the products in it
购物篮和里面的商品
A product exists in the shop's catalogue whether or not anyone has added it to a basket, and the same product sits in hundreds of baskets at once. Emptying one basket must not delete the product.
无论有没有人把它加入购物篮,商品都存在于商店的目录中,而且同一件商品可以同时出现在成百上千个购物篮里。清空一个购物篮,绝不能删除这件商品。
filled diamond = composition实心菱形 = 组合 hollow diamond = aggregation空心菱形 = 聚合 the diamond always sits at the whole end菱形总是在整体那一端
Worked example
例题讲解
The difference is visible in the constructor
区别体现在构造方法里
This is the most useful thing to recognise on a code-reading question, because the two look almost identical everywhere else.
这是在读代码的题目中最有用的辨认依据,因为除此之外,两者几乎处处看起来都差不多。
class Programme: def __init__(self, name, presenters): self.name = name # AGGREGATION: they already existed, they arrive as a parameter self.presenters = presenters # COMPOSITION: built right here, by and for this programme self.segments = [ Segment("Headlines", 5), Segment("Studio interview", 20) ] def running_time(self): # delegates to its parts total = 0 for s in self.segments: total += s.minutes return total
public class Programme { private String name; private List<Presenter> presenters; private List<Segment> segments; public Programme(String name, List<Presenter> presenters) { this.name = name; // AGGREGATION: handed in from outside, not created here this.presenters = presenters; // COMPOSITION: this object builds its own parts this.segments = new ArrayList<>(); this.segments.add(new Segment("Headlines", 5)); this.segments.add(new Segment("Studio interview", 20)); } }
The tell: where the part object is created. Composed parts are constructed inside the whole, so nothing else can ever hold a reference to them. Aggregated parts are constructed outside and passed in, which is precisely how they survive the whole and how two wholes can share the same one.
关键线索:部分对象是在哪里创建的。组合的部分是在整体内部构造的,所以没有任何别的东西能持有对它们的引用。聚合的部分是在外部构造再传入的,这正是它们能够比整体存活更久、以及两个整体能共享同一个部分的原因。
Worked example
例题讲解
Delete the programme and see what survives
删除节目,看看什么能留下来
Alderway cancels Evening Review. Press the button and watch which objects go with it. Morning Show is a second programme that happens to share a presenter.
Alderway 取消了 Evening Review。点击按钮,观察哪些对象随之消失。Morning Show 是另一个节目,恰好与它共用一位主持人。
Evening Review holds two segments of its own, and is rostered to Nadia and Tom. Nadia also presents Morning Show.
Tom is the interesting one. He presents nothing else, yet he still survives, because aggregation is about independent existence, not about being shared. Sharing is something aggregation makes possible, not something it requires.
Tom 是个有意思的例子。他不主持其他任何节目,但他仍然留了下来,因为聚合讲的是独立存在,而不是被共享。共享是聚合使之成为可能的事情,而不是它的必要条件。
Explainer
讲解
Choosing between them when you design
设计时如何在二者之间选择
Real example: Programme and its Segment objects, built in the constructor and owned outright.
实际例子:Programme 和它的 Segment 对象,在构造方法中创建,完全归它所有。
Advantage
优点
- The whole controls its parts completely (nothing outside can hold a reference and change a segment behind the programme's back, so the programme can always trust its own running time)
- 整体完全控制它的部分 (外部没有任何东西能持有引用并在节目背后修改片段,所以节目永远可以信任自己的总时长)
Disadvantage
缺点
- Tightly coupled, and not reusable (a segment cannot be lifted out and given to another programme, and the two classes now have to change together)
- 紧耦合,而且不可复用 (一个片段不能被取出来交给另一个节目,而且这两个类现在必须一起修改)
Real example: Programme and its Presenter objects, employed by the station and passed in.
实际例子:Programme 和它的 Presenter 对象,由电台雇用并传入。
Advantage
优点
- One object can serve many wholes (a presenter exists once in the system and appears on every programme they host, so updating their contact details updates it everywhere)
- 一个对象可以服务于多个整体 (一位主持人在系统中只存在一份,并出现在他主持的每个节目里,所以更新他的联系方式就会在所有地方同时更新)
Disadvantage
缺点
- The whole cannot rely on exclusive control (another part of the program holds the same object and may change it at any time, and deleting the whole leaves the part behind, which has to be tidied up separately)
- 整体不能指望独占控制 (程序的其他部分持有同一个对象,可能随时修改它,而删除整体会把部分留下来,需要另外清理)
Both are usually preferable to inheritance when the relationship is genuinely "has-a" rather than "is-a". A programme is not a kind of segment, and a segment is not a kind of programme, so no inheritance hierarchy would model this well however it were arranged.
当这种关系确实是"拥有(has-a)"而不是"是(is-a)"时,这两者通常都比继承更可取。一个节目不是一种片段,一个片段也不是一种节目,所以无论怎么安排,任何继承层次结构都无法很好地为此建模。
Try it yourself
动手试试
Prove the parts are shared, or not
证明各个部分是共享的,还是不共享
Two programmes, one shared presenter. The counter at the end is the proof: because both programmes hold the same Presenter object, incrementing it from either one is visible from the other. Try doing the same with a segment and watch it fail.
两个节目,共享一位主持人。结尾的计数器就是证明:因为两个节目持有的是同一个 Presenter 对象,从任何一个节目去增加它,另一个都能看到。试试对片段做同样的事,看它如何失败。
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 shared object references, but it isn’t full Python.
正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括共享的对象引用,但它不是完整的 Python。
Check your understanding
检查你的理解
A Playlist class receives Track objects as a constructor parameter, and the same Track appears on three different playlists. Deleting one playlist must not affect the others. Which relationship is this, and why?
一个 Playlist 类通过构造方法参数接收 Track 对象,同一个 Track 出现在三个不同的播放列表里。删除其中一个播放列表,绝不能影响其他的。这是哪种关系,为什么?
Common mistake
常见错误
B3.2.4B3.2.4 的这一常见模式RecurringCandidates justify their choice using how many parts there are rather than how long the parts live. "A programme has several segments, so it is composition" is not an argument, because aggregation involves several parts just as often. Quantity never distinguishes the two.
反复出现考生用有多少个部分来论证自己的选择,而不是用部分存活多久。"一个节目有好几个片段,所以是组合"不是论证,因为聚合同样经常涉及好几个部分。数量从来不能区分两者。
The second error is treating "the whole has a reference to the part" as evidence of composition. Both relationships hold references; that is what makes them both has-a relationships in the first place. What separates them is whether the part was created inside the whole and dies with it.
第二个错误是把"整体持有对部分的引用"当作组合的证据。两种关系都持有引用;这正是它们首先都属于"拥有"关系的原因。区分它们的,是部分究竟是不是在整体内部创建、并随整体一起消亡。
Answer frame that scores: state where the part is created → state what happens to it when the whole is destroyed → name the relationship that follows from those two facts.
能得分的答题框架:说明部分是在哪里创建的 → 说明整体被销毁时它会怎样 → 指出由这两个事实得出的关系名称。
What a weak answer looks like: “Programme and Presenter is composition because a programme is made up of its presenters.” It describes a has-a relationship correctly and then picks the wrong one, with no reference to lifetime at all.
较弱的答案是这样的:“Programme 和 Presenter 是组合,因为节目由它的主持人组成。”它正确地描述了一种"拥有"关系,然后选错了类型,完全没有提到生命周期。
What it should say: “Programme and Presenter is aggregation: presenters are created by the station and passed into the constructor, so the same presenter can appear on several programmes and still exists once a programme is cancelled. Programme and Segment is composition, because the segments are constructed inside Programme and are meaningless without it.” Creation point, lifetime, and the name that follows.
应该这样写:“Programme 和 Presenter 是聚合:主持人由电台创建并传入构造方法,所以同一位主持人可以出现在多个节目里,并且在某个节目被取消后仍然存在。Programme 和 Segment 是组合,因为片段是在 Programme 内部构造的,没有它就毫无意义。”创建位置、生命周期,以及由此得出的名称。
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[3]Explain why Programme and Segment is composition, while Programme and Presenter is aggregation.
[3]解释为什么 Programme 和 Segment 是组合,而 Programme 和 Presenter 是聚合。
Marking points
评分要点
- Programme and Segment is composition: a segment belongs to exactly one programme, is created as part of it, and is destroyed when the programme is deleted.
- Programme and Presenter is aggregation: a presenter exists independently, can work on several programmes, and continues to exist if a programme is cancelled.
- The difference is lifetime and ownership: the segment shares the programme's lifetime, the presenter does not.
- Programme 和 Segment 是组合:一个片段恰好属于一档节目,作为其一部分被创建,并在节目被删除时被销毁。
- Programme 和 Presenter 是聚合:一位主持人独立存在,可以参与多档节目,并在某档节目被取消时继续存在。
- 区别在于生命周期和所有权:片段共享节目的生命周期,主持人则不然。
[4]Alderway adds a StudioBooking class. A booking exists only for one programme and is discarded when that programme is cancelled. Construct the class relationship in code, and justify your choice.
[4]Alderway 新增了一个 StudioBooking 类。一个预订只对应一个节目,该节目被取消时它就被丢弃。用代码构建这种类之间的关系,并说明你的选择理由。
Marking points
评分要点
- A StudioBooking exists only for one programme and is discarded with it, so this is composition.
- In code: the Programme constructor creates its StudioBooking (self.booking = StudioBooking(...)), and nothing outside holds a reference to it.
- When the Programme object is deleted, its StudioBooking is no longer referenced and goes with it.
- Justification: the booking has no independent existence or meaning without its programme, which is exactly the composition relationship.
- 一次 StudioBooking 只为一档节目存在,并随它一同被丢弃,所以这是组合。
- 在代码中:Programme 构造函数创建它的 StudioBooking(self.booking = StudioBooking(...)),外部没有东西持有对它的引用。
- 当 Programme 对象被删除时,它的 StudioBooking 不再被引用,随之消失。
- 理由:这次预订离开它的节目就没有独立的存在或意义,这正是组合关系。
[4]A developer suggests making Programme inherit from Segment so it can reuse the minutes attribute. Evaluate this suggestion.
[4]一位开发者建议让 Programme 继承 Segment,以便复用 minutes 属性。评价这个建议。
Marking points
评分要点
- Inheritance models an is-a relationship, but a programme is not a kind of segment, so Programme inheriting from Segment is a false hierarchy.
- It would give Programme a single minutes attribute, when a programme actually has many segments each with their own minutes.
- It also drags in every other Segment method, which makes no sense for a Programme.
- The right approach is composition: Programme holds a list of Segment objects and computes its running time by summing their minutes.
- Evaluation: reject the suggestion; use composition, not inheritance, to reuse the attribute.
- 继承建模 is-a 关系,但一档节目不是一种片段,所以 Programme 继承 Segment 是一个错误的层级。
- 它会给 Programme 一个单一的 minutes 属性,而一档节目实际上有许多片段,每个都有自己的 minutes。
- 它还会拖入 Segment 的其他所有方法,对 Programme 毫无意义。
- 正确的做法是组合:Programme 持有一个 Segment 对象的列表,并通过把它们的 minutes 相加来计算自己的运行时间。
- 评价:拒绝该建议;用组合而不是继承来复用这个属性。
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.4, and every other IB CS 2027 statement.
免费账号:解锁 B3.2.4 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。