25-Comp-B11 Advanced Software Design · December 2018
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer) · Last updated
Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.
Adapter converts the interface of an existing class (the Adaptee) into the interface a client expects (the Target). GoF documents two structurally distinct ways to implement it, illustrating the general composition-vs-inheritance trade-off directly.
Class Adapter (inheritance-based). The Adapter INHERITS from Adaptee and implements Target, translating each Target call into the (already-inherited) Adaptee operations. Because it inherits Adaptee's entire implementation, it also inherits, and can be affected by, Adaptee's ENTIRE public/protected interface — the same "message leakage" hazard flagged for Question 11: client code that somehow obtains a reference typed as the concrete ClassAdapter can call inherited Adaptee operations that bypass the adaptation entirely. It is also bound at COMPILE time to exactly one Adaptee class and cannot adapt any of Adaptee's subclasses transparently, since inheritance is a fixed, single relationship chosen once.
Object Adapter (composition-based). The Adapter HOLDS a reference to a separate Adaptee instance and implements Target purely by forwarding each call to it. Only the operations the Adapter explicitly forwards are reachable through the Target interface — nothing of Adaptee's interface leaks through beyond what is deliberately exposed. Because the held reference is typed as Adaptee (or an Adaptee interface), the SAME Object Adapter transparently works with any Adaptee SUBCLASS supplied at construction time, and which concrete Adaptee it wraps can even be changed at runtime.
The principle, illustrated by the diagrams. "Favor object composition over class inheritance" says: when a class needs to reuse another class's behaviour, prefer HOLDING a reference to it (as Object Adapter does) over INHERITING from it (as Class Adapter does), because composition exposes only the deliberately-forwarded operations (no leakage), remains flexible at runtime (any subclass, swappable), and avoids the fragile-base-class coupling of inheriting a whole implementation just to reuse a fraction of it. GoF's own guidance follows this principle directly: it recommends Object Adapter as the DEFAULT choice, reserving Class Adapter for the narrower case where the language and situation make it clearly preferable (e.g. needing to override some of Adaptee's specific behaviour, which requires inheritance).