mirror of
https://github.com/rjNemo/design-patterns
synced 2026-06-06 02:26:40 +00:00
composite example
This commit is contained in:
parent
11b03fee22
commit
153ca441f0
9 changed files with 205 additions and 1 deletions
|
|
@ -13,3 +13,4 @@
|
|||
- [Structural Patterns](structural/README.md)
|
||||
- [Adapter](structural/adapter/README.md)
|
||||
- [Bridge](structural/bridge/README.md)
|
||||
- [Composite](structural/composite/README.md)
|
||||
|
|
|
|||
|
|
@ -4,3 +4,4 @@ Structural patterns explain how to assemble objects and classes into larger stru
|
|||
|
||||
- [Adapter](adapter/README.md)
|
||||
- [Bridge](bridge/README.md)
|
||||
- [Composite](composite/README.md)
|
||||
|
|
|
|||
|
|
@ -29,4 +29,4 @@ print("\n")
|
|||
implementation = ConcreteImplementationB()
|
||||
abstraction = Abstraction(implementation)
|
||||
|
||||
client_code(abstraction)
|
||||
client_code(abstraction)
|
||||
|
|
|
|||
41
structural/composite/README.md
Normal file
41
structural/composite/README.md
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# Composite
|
||||
|
||||
Composite is a structural design pattern that allows composing objects into a tree-like structure and work with the it as if it was a singular object.
|
||||
|
||||
## Summary
|
||||
|
||||
Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects.
|
||||
|
||||
## Problem
|
||||
|
||||
Using the Composite pattern makes sense only when the core model of your app can be represented as a tree.
|
||||
|
||||
For example, imagine that you have two types of objects: `Products` and `Boxes`. A `Box` can contain several `Products` as well as a number of smaller `Boxes`. These little `Boxes` can also hold some `Products` or even smaller `Boxes`, and so on.
|
||||
|
||||
Say you decide to create an ordering system that uses these classes. Orders could contain simple products without any wrapping, as well as boxes stuffed with products...and other boxes. How would you determine the total price of such an order?
|
||||
|
||||
You could try the direct approach: unwrap all the boxes, go over all the products and then calculate the total. That would be doable in the real world; but in a program, it’s not as simple as running a loop. You have to know the classes of `Products` and `Boxes` you’re going through, the nesting level of the boxes and other nasty details beforehand. All of this makes the direct approach either too awkward or even impossible.
|
||||
|
||||
## Solution
|
||||
|
||||
The Composite pattern suggests that you work with `Products` and `Boxes` through a common interface which declares a method for calculating the total price.
|
||||
|
||||
How would this method work? For a product, it’d simply return the product’s price. For a box, it’d go over each item the box contains, ask its price and then return a total for this box. If one of these items were a smaller box, that box would also start going over its contents and so on, until the prices of all inner components were calculated. A box could even add some extra cost to the final price, such as packaging cost.
|
||||
|
||||
The greatest benefit of this approach is that you don’t need to care about the concrete classes of objects that compose the tree. You don’t need to know whether an object is a simple product or a sophisticated box. You can treat them all the same via the common interface. When you call a method, the objects themselves pass the request down the tree.
|
||||
|
||||
## How to Implement
|
||||
|
||||
1. Make sure that the core model of your app can be represented as a tree structure. Try to break it down into simple elements and containers. Remember that containers must be able to contain both simple elements and other containers.
|
||||
|
||||
1. Declare the component interface with a list of methods that make sense for both simple and complex components.
|
||||
|
||||
1. Create a leaf class to represent simple elements. A program may have multiple different leaf classes.
|
||||
|
||||
1. Create a container class to represent complex elements. In this class, provide an array field for storing references to sub-elements. The array must be able to store both leaves and containers, so make sure it’s declared with the component interface type.
|
||||
|
||||
While implementing the methods of the component interface, remember that a container is supposed to be delegating most of the work to sub-elements.
|
||||
|
||||
1. Finally, define the methods for adding and removal of child elements in the container.
|
||||
|
||||
Keep in mind that these operations can be declared in the component interface. This would violate the Interface Segregation Principle because the methods will be empty in the leaf class. However, the client will be able to treat all the elements equally, even when composing the tree.
|
||||
0
structural/composite/__init__.py
Normal file
0
structural/composite/__init__.py
Normal file
53
structural/composite/component.py
Normal file
53
structural/composite/component.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class Component(ABC):
|
||||
"""
|
||||
The base Component class declares common operations for both simple and
|
||||
complex objects of a composition.
|
||||
"""
|
||||
|
||||
@property
|
||||
def parent(self) -> Component:
|
||||
return self._parent
|
||||
|
||||
@parent.setter
|
||||
def parent(self, parent) -> None:
|
||||
"""
|
||||
Optionally, the base Component can declare an interface for setting and
|
||||
accessing a parent of the component in a tree structure. It can also
|
||||
provide some default implementation for these methods.
|
||||
"""
|
||||
self._parent = parent
|
||||
|
||||
"""
|
||||
In some cases, it would be beneficial to define the child-management
|
||||
operations right in the base Component class. This way, you won't need to
|
||||
expose any concrete component classes to the client code, even during the
|
||||
object tree assembly. The downside is that these methods will be empty for
|
||||
the leaf-level components.
|
||||
"""
|
||||
|
||||
def add(self, component: Component) -> None:
|
||||
pass
|
||||
|
||||
def remove(self, component: Component) -> None:
|
||||
pass
|
||||
|
||||
def is_composite(self) -> bool:
|
||||
"""
|
||||
You can provide a method that lets the client code figure out whether a
|
||||
component can bear children.
|
||||
"""
|
||||
return False
|
||||
|
||||
@abstractmethod
|
||||
def operation(self) -> str:
|
||||
"""
|
||||
The base Component may implement some default behavior or leave it to
|
||||
concrete classes (by declaring the method containing the behavior as
|
||||
"abstract").
|
||||
"""
|
||||
pass
|
||||
44
structural/composite/composite.py
Normal file
44
structural/composite/composite.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
from dataclasses import dataclass, field
|
||||
from typing import List
|
||||
|
||||
from component import Component
|
||||
|
||||
|
||||
@dataclass
|
||||
class Composite(Component):
|
||||
"""
|
||||
The Composite class represents the complex components that may have
|
||||
children. Usually, the Composite objects delegate the actual work to their
|
||||
children and then "sum-up" the result.
|
||||
"""
|
||||
|
||||
_children: List[Component] = field(default_factory=list)
|
||||
|
||||
"""
|
||||
A composite object can add or remove other components (both simple or
|
||||
complex) to or from its child list.
|
||||
"""
|
||||
|
||||
def add(self, component: Component) -> None:
|
||||
self._children.append(component)
|
||||
component.parent = self
|
||||
|
||||
def remove(self, component: Component) -> None:
|
||||
self._children.remove(component)
|
||||
component.parent = None
|
||||
|
||||
def is_composite(self) -> bool:
|
||||
return True
|
||||
|
||||
def operation(self) -> str:
|
||||
"""
|
||||
The Composite executes its primary logic in a particular way. It
|
||||
traverses recursively through all its children, collecting and summing
|
||||
their results. Since the composite's children pass these calls to their
|
||||
children and so forth, the whole object tree is traversed as a result.
|
||||
"""
|
||||
|
||||
results = []
|
||||
for child in self._children:
|
||||
results.append(child.operation())
|
||||
return f"Branch({'+'.join(results)})"
|
||||
14
structural/composite/leaf.py
Normal file
14
structural/composite/leaf.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
from component import Component
|
||||
|
||||
|
||||
class Leaf(Component):
|
||||
"""
|
||||
The Leaf class represents the end objects of a composition. A leaf can't
|
||||
have any children.
|
||||
|
||||
Usually, it's the Leaf objects that do the actual work, whereas Composite
|
||||
objects only delegate to their sub-components.
|
||||
"""
|
||||
|
||||
def operation(self) -> str:
|
||||
return "Leaf"
|
||||
50
structural/composite/main.py
Normal file
50
structural/composite/main.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
from component import Component
|
||||
from composite import Composite
|
||||
from leaf import Leaf
|
||||
|
||||
|
||||
def client_code(component: Component) -> None:
|
||||
"""
|
||||
The client code works with all of the components via the base interface.
|
||||
"""
|
||||
print(f"RESULT: {component.operation()}", end="")
|
||||
|
||||
|
||||
def client_code2(component1: Component, component2: Component) -> None:
|
||||
"""
|
||||
Thanks to the fact that the child-management operations are declared in the
|
||||
base Component class, the client code can work with any component, simple
|
||||
or complex, without depending on their concrete classes.
|
||||
"""
|
||||
if component1.is_composite():
|
||||
component1.add(component2)
|
||||
print(f"RESULT: {component1.operation()}", end="")
|
||||
|
||||
|
||||
# This way the client code can support the simple leaf components...
|
||||
simple = Leaf()
|
||||
print("Client: I've got a simple component:")
|
||||
client_code(simple)
|
||||
print("\n")
|
||||
|
||||
# ...as well as the complex composites.
|
||||
tree = Composite()
|
||||
|
||||
branch1 = Composite()
|
||||
branch1.add(Leaf())
|
||||
branch1.add(Leaf())
|
||||
|
||||
branch2 = Composite()
|
||||
branch2.add(Leaf())
|
||||
|
||||
tree.add(branch1)
|
||||
tree.add(branch2)
|
||||
|
||||
print("Client: Now I've got a composite tree:")
|
||||
client_code(tree)
|
||||
print("\n")
|
||||
|
||||
print(
|
||||
"Client: I don't need to check the components classes even when managing the tree:"
|
||||
)
|
||||
client_code2(tree, simple)
|
||||
Loading…
Reference in a new issue