MCPcopy Create free account
hub / github.com/RefactoringGuru/design-patterns-python / Composite

Class Composite

src/Composite/Conceptual/main.py:112–161  ·  view source on GitHub ↗

EN: 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. RU: Класс Контейнер содержит сложные компоненты, которые могут иметь вложенные компоненты. О

Source from the content-addressed store, hash-verified

110
111
112class Composite(Component):
113 """
114 EN: The Composite class represents the complex components that may have
115 children. Usually, the Composite objects delegate the actual work to their
116 children and then "sum-up" the result.
117
118 RU: Класс Контейнер содержит сложные компоненты, которые могут иметь
119 вложенные компоненты. Обычно объекты Контейнеры делегируют фактическую
120 работу своим детям, а затем «суммируют» результат.
121 """
122
123 def __init__(self) -> None:
124 self._children: List[Component] = []
125
126 """
127 EN: A composite object can add or remove other components (both simple or
128 complex) to or from its child list.
129
130 RU: Объект контейнера может как добавлять компоненты в свой список вложенных
131 компонентов, так и удалять их, как простые, так и сложные.
132 """
133
134 def add(self, component: Component) -> None:
135 self._children.append(component)
136 component.parent = self
137
138 def remove(self, component: Component) -> None:
139 self._children.remove(component)
140 component.parent = None
141
142 def is_composite(self) -> bool:
143 return True
144
145 def operation(self) -> str:
146 """
147 EN: The Composite executes its primary logic in a particular way. It
148 traverses recursively through all its children, collecting and summing
149 their results. Since the composite's children pass these calls to their
150 children and so forth, the whole object tree is traversed as a result.
151
152 RU: Контейнер выполняет свою основную логику особым образом. Он проходит
153 рекурсивно через всех своих детей, собирая и суммируя их результаты.
154 Поскольку потомки контейнера передают эти вызовы своим потомкам и так
155 далее, в результате обходится всё дерево объектов.
156 """
157
158 results = []
159 for child in self._children:
160 results.append(child.operation())
161 return f"Branch({'+'.join(results)})"
162
163
164def client_code(component: Component) -> None:

Callers 1

main.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected