Composite patternIn 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.[1] Overview
The Composite[2] 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 design pattern can solve
When defining (1) Solutions the Composite design pattern describes
This enables clients to work through the See also the UML class and object diagram below. MotivationWhen dealing with Tree-structured data, programmers often have to discriminate between a leaf-node and a branch. This makes code more complex, and therefore, more error prone. The solution is an interface that allows treating complex and primitive objects uniformly. In object-oriented programming, a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality. This is known as a "has-a" relationship between objects.[4] The key concept is that you can manipulate a single instance of the object just as you would manipulate a group of them. The operations you can perform on all the composite objects often have a least common denominator relationship. For example, if defining a system to portray grouped shapes on a screen, it would be useful to define resizing a group of shapes to have the same effect (in some sense) as resizing a single shape. When to useComposite should be used when clients ignore the difference between compositions of objects and individual objects.[1] If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous. StructureUML class and object diagramIn the above UML class diagram, the The object collaboration diagram
shows the run-time interactions: In this example, the
There are two design variants for defining and implementing child-related operations
like adding/removing a child component to/from the container (
The Composite design pattern emphasizes uniformity over type safety. UML class diagram
VariationAs it is described in Design Patterns, the pattern also involves including the child-manipulation methods in the main Component interface, not just the Composite subclass. More recent descriptions sometimes omit these methods.[7] ExampleThis C++14 implementation is based on the pre C++98 implementation in the book. #include <iostream>
#include <string>
#include <list>
#include <memory>
#include <stdexcept>
typedef double Currency;
// declares the interface for objects in the composition.
class Equipment { // Component
public:
// implements default behavior for the interface common to all classes, as appropriate.
virtual const std::string& getName() {
return name;
}
virtual void setName(const std::string& name_) {
name = name_;
}
virtual Currency getNetPrice() {
return netPrice;
}
virtual void setNetPrice(Currency netPrice_) {
netPrice = netPrice_;
}
// declares an interface for accessing and managing its child components.
virtual void add(std::shared_ptr<Equipment>) = 0;
virtual void remove(std::shared_ptr<Equipment>) = 0;
virtual ~Equipment() = default;
protected:
Equipment() :name(""), netPrice(0) {}
Equipment(const std::string& name_) :name(name_), netPrice(0) {}
private:
std::string name;
Currency netPrice;
};
// defines behavior for components having children.
class CompositeEquipment : public Equipment { // Composite
public:
// implements child-related operations in the Component interface.
virtual Currency getNetPrice() override {
Currency total = Equipment::getNetPrice();
for (const auto& i:equipment) {
total += i->getNetPrice();
}
return total;
}
virtual void add(std::shared_ptr<Equipment> equipment_) override {
equipment.push_front(equipment_.get());
}
virtual void remove(std::shared_ptr<Equipment> equipment_) override {
equipment.remove(equipment_.get());
}
protected:
CompositeEquipment() :equipment() {}
CompositeEquipment(const std::string& name_) :equipment() {
setName(name_);
}
private:
// stores child components.
std::list<Equipment*> equipment;
};
// represents leaf objects in the composition.
class FloppyDisk : public Equipment { // Leaf
public:
FloppyDisk(const std::string& name_) {
setName(name_);
}
// A leaf has no children.
void add(std::shared_ptr<Equipment>) override {
throw std::runtime_error("FloppyDisk::add");
}
void remove(std::shared_ptr<Equipment>) override {
throw std::runtime_error("FloppyDisk::remove");
}
};
class Chassis : public CompositeEquipment {
public:
Chassis(const std::string& name_) {
setName(name_);
}
};
int main() {
// The smart pointers prevent memory leaks.
std::shared_ptr<FloppyDisk> fd1 = std::make_shared<FloppyDisk>("3.5in Floppy");
fd1->setNetPrice(19.99);
std::cout << fd1->getName() << ": netPrice=" << fd1->getNetPrice() << '\n';
std::shared_ptr<FloppyDisk> fd2 = std::make_shared<FloppyDisk>("5.25in Floppy");
fd2->setNetPrice(29.99);
std::cout << fd2->getName() << ": netPrice=" << fd2->getNetPrice() << '\n';
std::unique_ptr<Chassis> ch = std::make_unique<Chassis>("PC Chassis");
ch->setNetPrice(39.99);
ch->add(fd1);
ch->add(fd2);
std::cout << ch->getName() << ": netPrice=" << ch->getNetPrice() << '\n';
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 alsoReferences
External linksThe Wikibook Computer Science Design Patterns has a page on the topic of: Composite implementations in various languages
|