print(f"RESULT: {component1.operation()}", end="") if __name__ == "__main__": # This way the client code can support the simple leaf components... print("Start") 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)
from Composite import Composite from Operand import Operand from Add import Add from Multiply import Multiply #(10 + 25) * 4 + 52 * (3 + 6) expression = Composite(0) first_brackets = Add(Operand(10), Operand(25)) mul = Multiply(first_brackets, Operand(4)) second_brackets = Add(Operand(3), Operand(6)) mul2 = Multiply(second_brackets, Operand(52)) add = Add(mul, mul2) expression.add(add) print(expression.operation())
def client_code(component: Component): print(f"RESULT: {component.operation()}", end = "") def client_code2(composite: Component, component: Component): if composite.is_composite(): composite.add(component) print(f"RESULT: {component.operation()}", end = "") if __name__ == "__main__": simple = Leaf() print("Client: I've got a simple component:") client_code(simple) print("\n") tree = Composite() left_branch = Composite() left_branch.add(Leaf()) left_branch.add(Leaf()) right_branch = Composite() right_branch.add(Leaf()) tree.add(left_branch) tree.add(right_branch) 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) print("\n")