Patternadvanced
Whole-Part
Also called whole-part pattern, aggregate component, whole and parts.
The Whole-Part pattern aggregates components that form a semantic unit. The whole encapsulates its parts, organizes their collaboration, and gives clients one interface to them.
- Family
- structural-design
- Intent
- Aggregate components that together form a semantic unit into a whole that encapsulates the parts, organizes their collaboration and gives clients one interface.
Intent
Whole-Part is a structural pattern from Pattern-Oriented Software Architecture.1 It helps aggregate components that form a semantic unit.2 The aggregate is the whole, and the components are its parts. The whole encapsulates the parts, organizes how they work together, and gives clients one interface.
Problem
A car is made of many parts: a fuel injector, a distributor, spark plugs and pistons. When the car is driven, these parts work together in a fixed order. The driver has no direct access to any of them, and uses all of them through the controls of the car.2
Software has the same shape. Some objects are only useful together, and the rules of their collaboration belong to the group, not to each client. If each client reaches into the parts, each client must know the rules, and a change to one part breaks the clients.
Solution
Make the whole an object of its own. It creates or receives the parts, keeps them private, and gives an interface in terms of the unit. Each operation of the whole calls the parts in the right order. The participants of the car example are these:2
- The client is the driver, who uses all of the components through the interface of the whole.
- The whole is the car.
- The parts are the smaller systems: the fuel system, the ignition system and the cooling system.
Client
| drive()
v
+------------------- Whole (Car) --------------------+
| drive(): starter.crank(), engine.fire(), |
| wheels.turn() |
| |
| Starter Engine Wheels |
| (part) (part) (part) |
+-----------------------------------------------------+
the client has no reference to a part
Example
The example files show one program in each language. A Car creates a starter, an engine and wheels, and keeps them private. Its drive operation calls the three parts in order. The car then gets a new starter. The client code does not change, and the output shows the new part:
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
class Starter:
def crank(self):
return "crank the engine"
class NewStarter:
def crank(self):
return "crank the engine with the new starter"
class Engine:
def fire(self):
return "fire the cylinders"
class Wheels:
def turn(self):
return "turn the wheels"
class Car:
"""The whole: it creates its parts and keeps them private."""
def __init__(self):
self._starter = Starter()
self._engine = Engine()
self._wheels = Wheels()
def drive(self):
return ", ".join([self._starter.crank(), self._engine.fire(), self._wheels.turn()])
def replace_starter(self, starter):
self._starter = starter
car = Car()
print(f"drive: {car.drive()}")
car.replace_starter(NewStarter())
print(f"drive: {car.drive()}")
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. A leading underscore marks the parts as private by convention; the language does not stop access to them.
#include <iostream>
#include <memory>
#include <string>
struct StarterPart {
virtual ~StarterPart() = default;
virtual std::string crank() const = 0;
};
struct Starter : StarterPart {
std::string crank() const override { return "crank the engine"; }
};
struct NewStarter : StarterPart {
std::string crank() const override { return "crank the engine with the new starter"; }
};
class Car {
public:
std::string drive() const {
return starter_->crank() + ", " + engine_.fire() + ", " + wheels_.turn();
}
void replace_starter(std::unique_ptr<StarterPart> starter) { starter_ = std::move(starter); }
private:
struct Engine {
std::string fire() const { return "fire the cylinders"; }
};
struct Wheels {
std::string turn() const { return "turn the wheels"; }
};
// The car owns its parts: they are destroyed with it.
std::unique_ptr<StarterPart> starter_ = std::make_unique<Starter>();
Engine engine_;
Wheels wheels_;
};
int main() {
Car car;
std::cout << "drive: " << car.drive() << "\n";
car.replace_starter(std::make_unique<NewStarter>());
std::cout << "drive: " << car.drive() << "\n";
}
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. The parts are private members, so their lifetime is the lifetime of the whole, and
unique_ptrgives the whole sole ownership of the part that can be replaced.
interface StarterPart { String crank(); }
class Starter implements StarterPart {
public String crank() { return "crank the engine"; }
}
class NewStarter implements StarterPart {
public String crank() { return "crank the engine with the new starter"; }
}
class Car {
// The parts are private; the Engine and Wheels classes are private too.
private static final class Engine { String fire() { return "fire the cylinders"; } }
private static final class Wheels { String turn() { return "turn the wheels"; } }
private StarterPart starter = new Starter();
private final Engine engine = new Engine();
private final Wheels wheels = new Wheels();
String drive() {
return String.join(", ", starter.crank(), engine.fire(), wheels.turn());
}
void replaceStarter(StarterPart starter) { this.starter = starter; }
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
System.out.println("drive: " + car.drive());
car.replaceStarter(new NewStarter());
System.out.println("drive: " + car.drive());
}
}
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. Private nested classes make the parts invisible outside the whole, as
ThreadPoolExecutordoes with itsWorkerclass.
using System;
interface IStarterPart { string Crank(); }
class Starter : IStarterPart { public string Crank() => "crank the engine"; }
class NewStarter : IStarterPart { public string Crank() => "crank the engine with the new starter"; }
class Car
{
private sealed class Engine { public string Fire() => "fire the cylinders"; }
private sealed class Wheels { public string Turn() => "turn the wheels"; }
private IStarterPart starter = new Starter();
private readonly Engine engine = new();
private readonly Wheels wheels = new();
public string Drive() => string.Join(", ", starter.Crank(), engine.Fire(), wheels.Turn());
public void ReplaceStarter(IStarterPart starter) => this.starter = starter;
}
class Program
{
static void Main()
{
var car = new Car();
Console.WriteLine($"drive: {car.Drive()}");
car.ReplaceStarter(new NewStarter());
Console.WriteLine($"drive: {car.Drive()}");
}
}
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. Private nested classes and private fields hide the parts, and an interface describes the part that can be replaced.
class Starter {
crank() {
return "crank the engine";
}
}
class NewStarter {
crank() {
return "crank the engine with the new starter";
}
}
class Engine {
fire() {
return "fire the cylinders";
}
}
class Wheels {
turn() {
return "turn the wheels";
}
}
class Car {
// the parts: private fields that no client can reach
#starter = new Starter();
#engine = new Engine();
#wheels = new Wheels();
drive() {
return [this.#starter.crank(), this.#engine.fire(), this.#wheels.turn()].join(", ");
}
replaceStarter(starter) {
this.#starter = starter;
}
}
const car = new Car();
console.log(`drive: ${car.drive()}`);
car.replaceStarter(new NewStarter());
console.log(`drive: ${car.drive()}`);
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. Private
#fields hold the parts, so code outside the class cannot reach them.
interface StarterPart {
crank(): string;
}
class Starter implements StarterPart {
crank(): string {
return "crank the engine";
}
}
class NewStarter implements StarterPart {
crank(): string {
return "crank the engine with the new starter";
}
}
class Engine {
fire(): string {
return "fire the cylinders";
}
}
class Wheels {
turn(): string {
return "turn the wheels";
}
}
class Car {
#starter: StarterPart = new Starter();
readonly #engine = new Engine();
readonly #wheels = new Wheels();
drive(): string {
return [this.#starter.crank(), this.#engine.fire(), this.#wheels.turn()].join(", ");
}
replaceStarter(starter: StarterPart): void {
this.#starter = starter;
}
}
const car = new Car();
console.log(`drive: ${car.drive()}`);
car.replaceStarter(new NewStarter());
console.log(`drive: ${car.drive()}`);
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. The
StarterPartinterface says what a replacement part must do, and private fields hide the parts.
package main
import (
"fmt"
"strings"
)
type StarterPart interface{ Crank() string }
type Starter struct{}
func (Starter) Crank() string { return "crank the engine" }
type NewStarter struct{}
func (NewStarter) Crank() string { return "crank the engine with the new starter" }
type engine struct{}
func (engine) fire() string { return "fire the cylinders" }
type wheels struct{}
func (wheels) turn() string { return "turn the wheels" }
// Car is the whole. In a package of its own, its unexported fields and the
// unexported engine and wheels types are hidden from other packages.
type Car struct {
starter StarterPart
engine engine
wheels wheels
}
func NewCar() *Car { return &Car{starter: Starter{}} }
func (c *Car) Drive() string {
return strings.Join([]string{c.starter.Crank(), c.engine.fire(), c.wheels.turn()}, ", ")
}
func (c *Car) ReplaceStarter(s StarterPart) { c.starter = s }
func main() {
car := NewCar()
fmt.Println("drive:", car.Drive())
car.ReplaceStarter(NewStarter{})
fmt.Println("drive:", car.Drive())
}
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. Unexported fields and types hide the parts from other packages. Inside the package of the whole, they are visible.
mod car {
pub trait StarterPart {
fn crank(&self) -> String;
}
pub struct Starter;
impl StarterPart for Starter {
fn crank(&self) -> String {
"crank the engine".to_string()
}
}
pub struct NewStarter;
impl StarterPart for NewStarter {
fn crank(&self) -> String {
"crank the engine with the new starter".to_string()
}
}
struct Engine; // private to the module
struct Wheels;
impl Engine {
fn fire(&self) -> &'static str {
"fire the cylinders"
}
}
impl Wheels {
fn turn(&self) -> &'static str {
"turn the wheels"
}
}
pub struct Car {
starter: Box<dyn StarterPart>,
engine: Engine,
wheels: Wheels,
}
impl Car {
pub fn new() -> Car {
Car { starter: Box::new(Starter), engine: Engine, wheels: Wheels }
}
pub fn drive(&self) -> String {
format!("{}, {}, {}", self.starter.crank(), self.engine.fire(), self.wheels.turn())
}
pub fn replace_starter(&mut self, starter: Box<dyn StarterPart>) {
self.starter = starter;
}
}
}
fn main() {
let mut car = car::Car::new();
println!("drive: {}", car.drive());
car.replace_starter(Box::new(car::NewStarter));
println!("drive: {}", car.drive());
}
drive: crank the engine, fire the cylinders, turn the wheels
drive: crank the engine with the new starter, fire the cylinders, turn the wheels
- Verdict: idiom. The
Carstruct owns its parts, its fields are private to the module, andEngineandWheelsare private types.
Consequences
The benefits:2
- Changeable parts. A part can change without an effect on the client. If a starter fails, it is replaced, and the interface of the car stays the same for the driver.
- Separate concerns. Each concern is in a separate part, which makes complex strategies easier to implement. Many parts of a car are simple, but the whole is complex.
- Reuse. The parts of one whole can be used in other aggregates. The auto salvage industry takes a part from one car for use in another.
The costs:
- A larger interface on the whole. Each service that a client needs from a part must be an operation of the whole.
- Indirection. Each call goes through the whole, which forwards it to the parts.
The encapsulation is what keeps the whole correct. Here an order is a whole with lines as parts, and it keeps a running total. The order lets clients reach its list of lines, so a client adds a line directly, and the total is wrong:
This code runs but gives a wrong answer on purpose.
class Order:
def __init__(self):
self.lines = [] # the parts, open to every client
self.total = 0
def add_line(self, name, price):
self.lines.append((name, price))
self.total += price
order = Order()
order.add_line("pen", 4)
order.add_line("ink", 6)
order.lines.append(("paper", 5)) # bypasses the whole
print(f"lines: {len(order.lines)}, total: {order.total}")
lines: 3, total: 10
When the whole keeps the parts private and gives a read-only copy, every change goes through the whole:
class Order:
def __init__(self):
self._lines = []
self._total = 0
def add_line(self, name, price):
self._lines.append((name, price))
self._total += price
@property
def lines(self):
return tuple(self._lines) # a copy: no client can change the parts
@property
def total(self):
return self._total
order = Order()
order.add_line("pen", 4)
order.add_line("ink", 6)
order.add_line("paper", 5)
print(f"lines: {len(order.lines)}, total: {order.total}")
lines: 3, total: 15
When not to use it
- Clients need direct access to the parts, for example to use them in their own order. A Facade pattern gives a simple interface and still lets these clients use the parts.
- The parts do not form a unit, and there are no rules for their collaboration. A whole then only forwards calls.
- There is only one part. A wrapper around one object is a Delegation pattern or an adapter, not an aggregate.
Variants and related patterns
Composite. The Composite pattern composes objects into tree structures that represent part-whole hierarchies, and clients treat single objects and compositions in the same way.3 A composite shows its children to clients. A whole hides its parts.
Facade. A Facade pattern gives one interface to a set of interfaces in a subsystem.3 The subsystem classes stay available to the clients that need them, so a facade does not give the encapsulation of a whole.
Composition over inheritance. A whole gets its behaviour from parts that it holds, not from parent classes, as in Composition over inheritance.
Known uses
- Java: ThreadPoolExecutor.java at jdk-21-ga keeps its parts in private fields: a
BlockingQueue<Runnable> workQueueand aHashSet<Worker> workers.Workeris aprivate final class. A client gives a task to the pool throughexecute(Runnable command), and the task runs "in a new thread or in an existing pooled thread".4 - A car: the OOPSLA 98 workshop example. The driver uses the fuel, ignition and cooling systems only through the car.2
References
- Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad and Michael Stal, Pattern-Oriented Software Architecture, Volume 1: A System of Patterns, John Wiley and Sons, Whole-Part
- Examples to Accompany: Design Patterns, Elements of Reusable Object-Oriented Software, AG Communication Systems, 1999, introduction to the PoSA examples, page A-36; Whole-Part, page A-44
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4, Composite and Facade
- OpenJDK jdk-21-ga source, java/util/concurrent/ThreadPoolExecutor.java, class at line 329, workQueue at line 454, workers at line 475, Worker at line 608, execute at line 1339
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag TFBD5H Edit this page History Report an error Markdown