Composite pattern

In software engineering, the composite pattern is a partitioning design pattern.

Uses your system voice; voice and rate in settings.

Snapshot

≈ 4 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Overview

The Composite design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

Problems

The Composite pattern solves these problems: Represent a part-whole hierarchy so that clients can treat part and whole objects uniformly. Represent a part-whole hierarchy as tree structure. When defining (1) Part objects and (2) Whole objects that act as containers for Part objects, clients must treat them separately, which complicates client code.

Solution

Define a unified Component interface for part ( Leaf ) objects and whole ( Composite ) objects. Individual Leaf objects implement the Component interface directly, and Composite objects forward requests to their child components.

This enables clients to work through the Component interface to treat Leaf and Composite objects uniformly: Leaf objects perform a request directly, and Composite objects forward the request to their child components recursively downwards the tree structure. This makes client classes easier to implement, change, test, and reuse. See also the UML class and object diagram below.

Structure

import std; using std::runtime_error; using std::shared_ptr; using std::string; using std::unique_ptr; using std::vector; // Component object // declares the interface for objects in the composition. class Equipment { private: string name; double netPrice; protected: Equipment() = default; explicit Equipment(const string& name): name{name}, netPrice{0} {} public: // implements default behavior for the interface common to all classes, as appropriate. nodiscard virtual const string& getName() const noexcept { return name; } virtual void setName(const string& name) noexcept { this->name = name; } nodiscard virtual double getNetPrice() const noexcept { return netPrice; } virtual void setNetPrice(double netPrice) noexcept { this->netPrice = netPrice; } // declares an interface for accessing and managing its child components. virtual void add(shared_ptr ) = 0; virtual void remove(shared_ptr ) = 0; virtual ~Equipment() = default; }; // Composite object // defines behavior for components having children. class CompositeEquipment: public Equipment { private: // stores child components. using EquipmentList = vector >; EquipmentList equipments; protected: CompositeEquipment() = default; explicit CompositeEquipment(const string& name): Equipment(name), equipments{EquipmentList()} {} public: // implements child-related operations in the Component interface. nodiscard virtual double getNetPrice() const noexcept override { double total = Equipment::getNetPrice(); for (const Equipment& i: equipments) { total += i->getNetPrice(); } return total; } virtual void add(shared_ptr equipment) override { equipments.push_back(equipment.get()); } virtual void remove(shared_ptr equipment) override { equipments.remove(equipment.get()); } }; // Leaf object // represents leaf objects in the composition. class FloppyDisk: public Equipment { public: explicit FloppyDisk(const String& name): Equipment(name) {} // A leaf has no children. void add(shared_ptr ) override { throw runtime_error("FloppyDisk::add() cannot be called!"); } void remove(shared_ptr ) override { throw runtime_error("FloppyDisk::remove() cannot be called!"); } }; class Chassis: public CompositeEquipment { public: explicit Chassis(const string& name): CompositeEquipment(name) {} }; int main() { shared_ptr fd1 = std::make_shared ("3.5in Floppy"); fd1->setNetPrice(19.99); std::println("{}: netPrice = {}", fd1->getName(), fd1->getNetPrice); shared_ptr fd2 = std::make_shared ("5.25in Floppy"); fd2->setNetPrice(29.99); std::println("{}: netPrice = {}", fd2->getName(), fd2->getNetPrice); unique_ptr ch = std::make_unique ("PC Chassis"); ch->setNetPrice(39.99); ch->add(fd1); ch->add(fd2); std::println("{}: netPrice = {}", ch->getName(), ch->getNetPrice); fd2->add(fd1); } The program output is 3.5in Floppy: netPrice=19.99 5.25in Floppy: netPrice=29.99 PC Chassis: netPrice=89.97 terminate called after throwing an instance of 'std::runtime_error' what(): FloppyDisk::add

See also

Perl Design Patterns Book Mixin Law of Demeter

Text derived from https://en.wikipedia.org/w/index.php?oldid=1360477607 under CC BY-SA 4.0; modifications have been made.

Sources cited in this revision

6 named source(s) extracted from the cited revision. A source with no author is shown by its publication; nothing is invented.