### Run Example Script Source: https://github.com/refactoringguru/design-patterns-python/blob/main/README.md Demonstrates how to execute a design pattern example script from the command line using the Python executable. This is the general command for running any example within the project. ```sh python src/Path-to-example/main.py ``` -------------------------------- ### Decorator Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Decorator/Conceptual/Output.txt Demonstrates the client's interaction with the Decorator pattern. It shows how components are wrapped and how the client perceives the decorated object. ```python Client: I've got a simple component: RESULT: ConcreteComponent Client: Now I've got a decorated component: RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent)) ``` -------------------------------- ### Multi-language Comment Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/README.md Illustrates how comments can include language tags (e.g., EN, RU) to support multiple language versions of code examples on a website. This allows for a single code file to be presented in different languages. ```python """ EN: All products families have the same varieties (MacOS/Windows). This is a MacOS variant of a button. RU: Все семейства продуктов имеют одни и те же вариации (MacOS/Windows). Это вариант кнопки под MacOS. """ ``` -------------------------------- ### Composite Pattern: Client Usage Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Composite/Conceptual/Output.txt Demonstrates how a client can interact with both Leaf and Branch components uniformly through the Composite pattern. ```python # Client code leaf1 = Leaf("Leaf") leaf2 = Leaf("Leaf") leaf3 = Leaf("Leaf") branch1 = Branch("Branch") branch1.add(leaf1) branch1.add(leaf2) branch2 = Branch("Branch") branch2.add(leaf3) composite_tree = Branch("Branch") composite_tree.add(branch1) composite_tree.add(branch2) print(composite_tree.operation()) ``` -------------------------------- ### PEP 8 Style Guide Compliance Source: https://github.com/refactoringguru/design-patterns-python/blob/main/requirements.txt This snippet demonstrates adherence to the PEP 8 style guide for Python code, ensuring readability and consistency. It covers naming conventions, indentation, line length, and other formatting rules. ```python import os def calculate_area(length, width): """Calculates the area of a rectangle.""" if length <= 0 or width <= 0: raise ValueError("Length and width must be positive.") return length * width class MyClass: def __init__(self, value): self.value = value def display_value(self): print(f"The value is: {self.value}") if __name__ == "__main__": rect_length = 10 rect_width = 5 area = calculate_area(rect_length, rect_width) print(f"The area is: {area}") obj = MyClass(100) obj.display_value() ``` -------------------------------- ### Strategy Pattern Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Strategy/Conceptual/Output.txt Demonstrates the Strategy pattern for sorting data. It allows the algorithm to be selected at runtime. The client interacts with a Context object, which uses a Strategy object to perform the sorting. ```python from abc import ABC, abstractmethod class Strategy(ABC): """The Strategy interface declares operations common to all supported versions of some algorithm.""" @abstractmethod def do_algorithm(self, data): pass class ConcreteStrategyA(Strategy): """Concrete Strategies implement the algorithm using the Strategy interface.""" def do_algorithm(self, data): return sorted(data) class ConcreteStrategyB(Strategy): """Also concrete strategy. Here we just different algorithm. """ def do_algorithm(self, data): return [x for x in reversed(sorted(data))] class Context: """The Context defines the interface of interest to clients.""" def __init__(self, strategy: Strategy) -> None: """The Context is configured with a Strategy object.""" self._strategy = strategy @property def strategy(self) -> Strategy: """The Context allows replacing the Strategy object at runtime.""" return self._strategy @strategy.setter def strategy(self, strategy: Strategy) -> None: """The Context delegates the work to a Strategy object instead of implementing multiple versions of the algorithm on its own.""" self._strategy = strategy def do_some_business_logic(self) -> None: """The Context delegates the actual work to a Strategy object.""" print("Context: Sorting data using the strategy (not sure how it'll do it)") result = self._strategy.do_algorithm(list('a,b,c,d,e'.split(","))) print(",".join(result)) if __name__ == "__main__": # The client code can be configured with different strategies. client_code = str( "Client: Strategy is set to normal sorting.\n" "Context: Sorting data using the strategy (not sure how it'll do it)\n" "a,b,c,d,e\n\n" "Client: Strategy is set to reverse sorting.\n" "Context: Sorting data using the strategy (not sure how it'll do it)\n" "e,d,c,b,a" ) print(client_code) context = Context(ConcreteStrategyA()) context.do_some_business_logic() print("\n") context.strategy = ConcreteStrategyB() context.do_some_business_logic() ``` -------------------------------- ### State Pattern Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/State/Conceptual/Output.txt Demonstrates the State design pattern in Python. It shows how an object can alter its behavior when its internal state changes, appearing as if the object changed its class. This example uses a Context class and several State classes (ConcreteStateA, ConcreteStateB) to manage different states and transitions. ```python class Context: """The Context defines the interface of interest to clients. It also maintains a reference to an instance of a ConcreteState subclass that defines the current state of the Context.""" _state = None def __init__(self, state): self._change_state(state) def _change_state(self, state): """Ask state about its behavior.""" print(f"Context: Transition to {state.__class__.__name__}") self._state = state self._state.context = self def request1(self): """Delegates the request to a.– the current state object.""" self._state.handle1() def request2(self): """Delegates the request to a.– the current state object.""" self._state.handle2() class State(object): """Common interface to all supported states.""" context = None def handle1(self): """For each ConcreteState class, implement a behavior that makes sense for the state of the Context.""" raise NotImplementedError def handle2(self): """For each ConcreteState class, implement a behavior that makes sense for the state of the Context.""" raise NotImplementedError class ConcreteStateA(State): """ConcreteStateA handles request1. ConcreteStateA wants to change the state of the context.""" def handle1(self): print("ConcreteStateA handles request1.") print("ConcreteStateA wants to change the state of the context.") self._change_state(ConcreteStateB()) def handle2(self): print("ConcreteStateA cannot handle request2.") class ConcreteStateB(State): """ConcreteStateB handles request2. ConcreteStateB wants to change the state of the context.""" def handle1(self): print("ConcreteStateB cannot handle request1.") def handle2(self): print("ConcreteStateB handles request2.") print("ConcreteStateB wants to change the state of the context.") self._change_state(ConcreteStateA()) if __name__ == '__main__': # Client code context = Context(ConcreteStateA()) context.request1() context.request2() context.request1() ``` -------------------------------- ### Singleton Pattern Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Singleton/Conceptual/ThreadSafe/Output.txt Demonstrates the Singleton design pattern in Python. It ensures that a class only has one instance and provides a global point of access to it. The output indicates whether the singleton was reused or if multiple instances were created. ```python class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls) return cls._instance if __name__ == "__main__": s1 = Singleton() s2 = Singleton() print("FOO") print("FOO") if s1 is s2: print("Singleton was reused (yay!)") else: print("Singleton was created twice (booo!!)") ``` -------------------------------- ### Builder Pattern Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Builder/Conceptual/Output.txt Demonstrates the Builder pattern for constructing complex objects step by step. It separates the construction of a complex object from its representation, allowing the same construction process to create different representations. ```python class Builder: def reset(self): pass def produce_part_a(self): pass def produce_part_b(self): pass def produce_part_c(self): pass class ConcreteBuilder1(Builder): def __init__(self): self.product = Product1() def reset(self): self.product = Product1() def produce_part_a(self): self.product.parts.append("PartA1") def produce_part_b(self): self.product.parts.append("PartB1") def produce_part_c(self): self.product.parts.append("PartC1") class Product1: def __init__(self): self.parts = [] class Director: def __init__(self): self.builder = None def set_builder(self, builder): self.builder = builder def build_minimal_viable_product(self): self.builder.produce_part_a() def build_full_featured_product(self): self.builder.produce_part_a() self.builder.produce_part_b() self.builder.produce_part_c() # Client code director = Director() builder = ConcreteBuilder1() director.set_builder(builder) director.build_minimal_viable_product() product1 = builder.product print(f"Product parts: {product1.parts}") builder.reset() director.build_full_featured_product() product2 = builder.product print(f"Product parts: {product2.parts}") # Custom product builder.reset() builder.produce_part_a() builder.produce_part_b() product3 = builder.product print(f"Product parts: {product3.parts}") ``` -------------------------------- ### Memento Pattern Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Memento/Conceptual/Output.txt This Python code demonstrates the Memento design pattern. It includes an Originator class that holds the state, a Memento class to store the state, and a Caretaker class to manage the mementos. The client code shows how to save and restore the Originator's state. ```python import copy from datetime import datetime class Memento: """Memento interface. Stores the state of the Originator.""" def __init__(self, state): self._state = state @property def state(self): return self._state class Originator: """Originator knows how to store a state beginning with Memento.""" _state = None @property def state(self): return self._state @state.setter def state(self, state): print("Originator: Setting state to...", state) self._state = state def save(self): """Saves the current state to a new Memento.""" print("Originator: Saving Originator's state...") return Memento(self._state) def restore(self, memento): """Restores the Originator's state from a Memento.""" print("Originator: Restoring state from Memento...") self._state = memento.state class Caretaker: """Caretaker will not change the saved state's value.""" def __init__(self): self._mementos = [] self._dates = [] def save(self, originator): """Saves the Originator's state.""" self._mementos.append(originator.save()) self._dates.append(datetime.now()) print("Caretaker: State saved at", self._dates[-1]) def restore(self, originator, index): """Restores the Originator's state from a specific Memento.""" if not len(self._mementos) == 0: try: originator.restore(self._mementos[index]) print("Caretaker: State restored to: " + str(self._dates[index])) except: print("Caretaker: Error restoring state.") else: print("Caretaker: No states to restore.") def show_history(self): """Displays the history of saved states.""" print("\nCaretaker: Here's the list of mementos:") for i, memento in enumerate(self._mementos): print(f"{self._dates[i].strftime('%Y-%m-%d %H:%M:%S')}", f" / ({memento.state[:10]}...)") if __name__ == '__main__': originator = Originator() originator.state = "Super-duper-super-puper-super." caretaker = Caretaker() caretaker.save(originator) caretaker.show_history() print("\nOriginator: My state has changed to: wQAehHYOqVSlpEXjyIcgobrxsZUnat") originator.state = "wQAehHYOqVSlpEXjyIcgobrxsZUnat" caretaker.save(originator) caretaker.show_history() print("\nOriginator: My state has changed to: lHxNORKcsgMWYnJqoXjVCbQLEIeiSp") originator.state = "lHxNORKcsgMWYnJqoXjVCbQLEIeiSp" caretaker.save(originator) caretaker.show_history() print("\nClient: Now, let's rollback!") caretaker.restore(originator, 2) print("\nClient: Once more!") caretaker.restore(originator, 1) ``` -------------------------------- ### Chain of Responsibility Pattern Example Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/ChainOfResponsibility/Conceptual/Output.txt Demonstrates the Chain of Responsibility pattern where a request is passed along a chain of handlers. Each handler decides either to process the request or to pass it to the next handler in the chain. ```python class MonkeyHandler(object): def handle(self, request): if request == "Banana": return f"Monkey wants {request}" else: return super().handle(request) class SquirrelHandler(object): def handle(self, request): if request == "Nut": return f"Squirrel wants {request}" else: return super().handle(request) class DogHandler(object): def handle(self, request): if request == "Meatball": return f"Dog wants {request}" else: return super().handle(request) def client_code(handler): for food in ["Nut", "Banana", "Cup of coffee"]: print(f"Client: Who wants a {food}?\n") result = handler.handle(food) if result: print(f" {result}", end="\n\n") else: print(f" {food} was left untouched.", end="\n\n") # The client code is usually placed into a separate class that handles requests. print("Chain: Monkey > Squirrel > Dog") monkey = MonkeyHandler() squirrel = SquirrelHandler() dog = DogHandler() monkey.next_handler(squirrel).next_handler(dog) client_code(monkey) print("Subchain: Squirrel > Dog") squirrel_only = SquirrelHandler() dog_only = DogHandler() squirrel_only.next_handler(dog_only) for food in ["Nut", "Banana", "Cup of coffee"]: print(f"Client: Who wants a {food}?\n") result = squirrel_only.handle(food) if result: print(f" {result}", end="\n\n") else: print(f" {food} was left untouched.", end="\n\n") ``` -------------------------------- ### Facade Pattern Initialization and Action Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Facade/Conceptual/Output.txt Demonstrates the Facade pattern by initializing subsystems and then commanding them to perform an action. The Facade acts as a simplified interface to a complex subsystem. ```python class Subsystem1: def go(self): return "Subsystem1: Go!" class Subsystem2: def fire(self): return "Subsystem2: Fire!" class Facade: def __init__(self): self.subsystem1 = Subsystem1() self.subsystem2 = Subsystem2() print("Facade initializes subsystems:") print("Subsystem1: Ready!") print("Subsystem2: Get ready!") def execute_action(self): print("Facade orders subsystems to perform the action:") print(self.subsystem1.go()) print(self.subsystem2.fire()) # Usage facade = Facade() facade.execute_action() ``` -------------------------------- ### Command Pattern - Simple Command Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Command/Conceptual/Output.txt Illustrates the basic Command pattern where an Invoker executes a simple command. The SimpleCommand class encapsulates a request as an object. ```python class SimpleCommand(Command): """Simple command""" def __init__(self, payload: str): self._payload = payload def execute(self) -> None: print(f"SimpleCommand: See, I can do simple things like printing ({self._payload})") ``` -------------------------------- ### Adapter Pattern Implementation Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Adapter/Conceptual/class/Output.txt This Python code demonstrates the Adapter design pattern. It includes the Target interface, the Adaptee with an incompatible interface, and the Adapter class that makes the Adaptee compatible with the Target. The Client class then uses the Adapter to interact with the Adaptee. ```python class Target: """The Target defines the domain-specific interface used by the client code.""" def request(self) -> str: return "Target: The default target's behavior." class Adaptee: """The Adaptee contains some useful behavior, but its interface is incompatible with the existing client code. The Adaptee needs some adaptation to work with the client.""" def specific_request(self) -> str: return ".eetpadA eht fo roivaheb laicepS" class Adapter(Target): """The Adapter allows the Adaptee class to work with the Target interface. It implements the Target interface and delegates the actual work to an Adaptee instance.""" def __init__(self, adaptee: Adaptee) -> None: self._adaptee = adaptee def request(self) -> str: return f"Adapter: ({self._adaptee.specific_request()[::-1]}) " def client_code(target: Target) -> None: """The client code works with an instance of a Target, as usual.""" print(target.request(), end="\n") if __name__ == '__main__': print("Client: I can work just fine with the Target objects:") target = Target() client_code(target) print("\nClient: The Adaptee class has a weird interface. See, I don't understand it:") adaptee = Adaptee() print(f"Adaptee: {adaptee.specific_request()}", end="\n") print("\nClient: But I can work with it via the Adapter:") adapter = Adapter(adaptee) client_code(adapter) ``` -------------------------------- ### Adapter Pattern Implementation Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Adapter/Conceptual/object/Output.txt This Python code demonstrates the Adapter design pattern. It includes the Target interface, the Adaptee with an incompatible interface, and the Adapter class that makes the Adaptee compatible with the Target. The Client class then uses the Adapter to interact with the Adaptee. ```python class Target: """The Target defines the domain-specific interface used by the client code.""" def request(self) -> str: return "Target: The default target's behavior." class Adaptee: """The Adaptee contains some useful behavior, but its interface is incompatible with the existing client code. The Adaptee needs some adaptation to work with the client.""" def specific_request(self) -> str: return ".eetpadA eht fo roivaheb laicepS" class Adapter(Target): """The Adapter allows the Adaptee class to work with the Target interface. It implements the Target interface and delegates the actual work to an Adaptee instance.""" def __init__(self, adaptee: Adaptee) -> None: self._adaptee = adaptee def request(self) -> str: return f"Adapter: ({self._adaptee.specific_request()[::-1]}) " def client_code(target: Target) -> None: """The client code works with an instance of a Target, as usual.""" print(target.request(), end="\n") if __name__ == '__main__': print("Client: I can work just fine with the Target objects:") target = Target() client_code(target) print("\nClient: The Adaptee class has a weird interface. See, I don't understand it:") adaptee = Adaptee() print(f"Adaptee: {adaptee.specific_request()}", end="\n") print("\nClient: But I can work with it via the Adapter:") adapter = Adapter(adaptee) client_code(adapter) ``` -------------------------------- ### Visitor Pattern - Client Code Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Visitor/Conceptual/Output.txt Demonstrates how client code interacts with different concrete visitors through the base Visitor interface. This allows for the addition of new operations to the object structure without modifying the objects themselves. ```python class Client: def client_code(self, visitor): # Client code works with all visitors via the base Visitor interface visitor.visit_concrete_component_a(self.component_a) visitor.visit_concrete_component_b(self.component_b) # ... other methods ``` -------------------------------- ### Bridge Pattern: Abstraction and Concrete Implementation Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Bridge/Conceptual/Output.txt Demonstrates the core concept of the Bridge pattern. The Abstraction defines an interface for the control, while ConcreteImplementationA provides a specific implementation for platform A. This decouples the abstraction from its implementation. ```python class Abstraction: def __init__(self, implementation): self._implementation = implementation def operation(self): return self._implementation.operation_impl() class ConcreteImplementationA: def operation_impl(self): return "Here's the result on the platform A." # Usage: implementation_a = ConcreteImplementationA() abstraction = Abstraction(implementation_a) print(abstraction.operation()) ``` -------------------------------- ### Command Pattern - Complex Command Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Command/Conceptual/Output.txt Demonstrates the Command pattern with a more complex scenario involving a Receiver. The ComplexCommand delegates the execution to a Receiver object. ```python class ComplexCommand(Command): """Complex command""" def __init__(self, receiver: Receiver, a: str, b: str): self._receiver = receiver self._a = a self._b = b def execute(self) -> None: print("ComplexCommand: Complex stuff should be done by a receiver object") self._receiver.do_something(self._a) self._receiver.do_something_else(self._b) ``` -------------------------------- ### Proxy Pattern Implementation Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Proxy/Conceptual/Output.txt This Python code demonstrates the Proxy design pattern. It includes a RealSubject class, a Proxy class that controls access to the RealSubject, and client code that interacts with both. ```python class RealSubject: def request(self): print("RealSubject: Handling request.") class Proxy: def __init__(self, real_subject): self._real_subject = real_subject def request(self): if self.check_access(): self._real_subject.request() self.log_access() else: print("Proxy: Access denied.") def check_access(self): print("Proxy: Checking access prior to firing a real request.") return True def log_access(self): print("Proxy: Logging the time of request.") # Client code print("Client: Executing the client code with a real subject:") real_subject = RealSubject() real_subject.request() print("\nClient: Executing the same client code with a proxy:") proxy = Proxy(real_subject) proxy.request() ``` -------------------------------- ### Flyweight Factory and Client Interaction Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Flyweight/Conceptual/Output.txt This snippet shows the interaction between the Flyweight Factory, the Client, and the Flyweight objects. It highlights how the factory reuses existing flyweights or creates new ones based on the requested state, and how flyweights display their shared and unique states. ```python class Flyweight: """Flyweight interface and a common implementation.""" def __init__(self, shared_state): self._shared_state = shared_state def operation(self, unique_state): """Prints the shared and unique state.""" print(f"Displaying shared ({self._shared_state}) and unique ({unique_state}) state.") class FlyweightFactory: """Factory methods for getting flyweight objects.""" def __init__(self): self._flyweights = {} def get(self, key) -> 'Flyweight': """Returns a flyweight object by key.""" if key not in self._flyweights: print("FlyweightFactory: Can't find a flyweight, creating new one.") self._flyweights[key] = Flyweight(key) else: print("FlyweightFactory: Reusing existing flyweight.") return self._flyweights[key] def list_flyweights(self): count = len(self._flyweights) print(f"FlyweightFactory: I have {count} flyweights:") for key in self._flyweights: print(f"\t{key}") # Client code if __name__ == "__main__": factory = FlyweightFactory() # Adding first car factory.get("Camaro2018_Chevrolet_pink").operation( "CL234IR", "James Doe" ) # Adding second car factory.get("C300_Mercedes Benz_black").operation( "C500_Mercedes Benz_red", "John Doe" ) factory.list_flyweights() print("\nClient: Adding a car to database.\n") # Adding third car, reusing existing flyweight factory.get("BMW_M5_red").operation( "CL234IR", "James Doe" ) # Adding fourth car, creating new flyweight factory.get("BMW_X1_red").operation( "CL234IR", "James Doe" ) factory.list_flyweights() ``` -------------------------------- ### Command Pattern - Receiver Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Command/Conceptual/Output.txt Defines the Receiver class which performs the actual work. The Receiver contains the business logic that commands will execute. ```python class Receiver: """Receiver classes usually support multiple operations""" def __init__(self): self._data = None def do_something(self, a: str) -> None: nonlocal self self._data = a print(f"Receiver: Working on ({self._data})", end="") def do_something_else(self, b: str) -> None: nonlocal self self._data = b print(f"Receiver: Also working on ({self._data})", end="") ``` -------------------------------- ### Bridge Pattern: Extended Abstraction and Different Implementation Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Bridge/Conceptual/Output.txt Extends the Abstraction with additional functionality. ExtendedAbstraction inherits from Abstraction and adds its own operation. ConcreteImplementationB provides an alternative implementation for platform B, demonstrating the flexibility of the Bridge pattern. ```python class ExtendedAbstraction(Abstraction): def extended_operation(self): return self._implementation.operation_impl() + "\nAnd extended functionality." class ConcreteImplementationB: def operation_impl(self): return "Here's the result on the platform B." # Usage: implementation_b = ConcreteImplementationB() extended_abstraction = ExtendedAbstraction(implementation_b) print(extended_abstraction.operation()) print(extended_abstraction.extended_operation()) ``` -------------------------------- ### Template Method Pattern - ConcreteClass2 Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/TemplateMethod/Conceptual/Output.txt Illustrates the Template Method pattern with a different concrete subclass. ConcreteClass2 overrides a hook method and provides its own implementation for an operation, showcasing subclass customization within the algorithm's structure. ```python class AbstractClass: def template_method(self) -> None: self.operation1() self.hook1() self.operation2() def operation1(self) -> None: print("AbstractClass says: I am doing the bulk of the work") def operation2(self) -> None: print("AbstractClass says: But I let subclasses override some operations") def hook1(self) -> None: pass class ConcreteClass2(AbstractClass): def operation1(self) -> None: print("ConcreteClass2 says: Implemented Operation1") def hook1(self) -> None: print("ConcreteClass2 says: Overridden Hook1") def operation2(self) -> None: print("ConcreteClass2 says: Implemented Operation2") def client_code(abstract_class: AbstractClass): abstract_class.template_method() print("Same client code can work with different subclasses:") client_code(ConcreteClass2()) ``` -------------------------------- ### Template Method Pattern - ConcreteClass1 Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/TemplateMethod/Conceptual/Output.txt Demonstrates the Template Method pattern where an abstract class defines the skeleton of an algorithm, deferring some steps to subclasses. ConcreteClass1 provides specific implementations for the operations defined by the abstract class. ```python class AbstractClass: def template_method(self) -> None: self.operation1() self.hook1() self.operation2() def operation1(self) -> None: print("AbstractClass says: I am doing the bulk of the work") def operation2(self) -> None: print("AbstractClass says: But I let subclasses override some operations") def hook1(self) -> None: pass class ConcreteClass1(AbstractClass): def operation1(self) -> None: print("ConcreteClass1 says: Implemented Operation1") def operation2(self) -> None: print("ConcreteClass1 says: Implemented Operation2") def client_code(abstract_class: AbstractClass): abstract_class.template_method() print("Same client code can work with different subclasses:") client_code(ConcreteClass1()) ``` -------------------------------- ### Command Pattern - Invoker Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Command/Conceptual/Output.txt The Invoker class holds a command and delegates all work to it. It does not know which command it is executing. ```python class Invoker: """Invoker holds a command and delegates it to do the work""" def __init__(self) -> None: self._on_start = None self._on_finish = None def set_on_start(self, command: Command): self._on_start = command def set_on_finish(self, command: Command): self._on_finish = command def do_something_important(self) -> None: print("Invoker: Does anybody want something done before I begin?") if isinstance(self._on_start, Command): self._on_start.execute() print("Invoker: ...doing something really important...") print("Invoker: Does anybody want something done after I finish?") if isinstance(self._on_finish, Command): self._on_finish.execute() ``` -------------------------------- ### Singleton Pattern Implementation Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Singleton/Conceptual/NonThreadSafe/Output.txt This Python code implements the Singleton design pattern. It ensures that only one instance of the `Singleton` class can be created. Subsequent attempts to create an instance will return the existing one. This is achieved by controlling the instance creation process within the class itself. ```python class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls) return cls._instance if __name__ == "__main__": s1 = Singleton() s2 = Singleton() if s1 is s2: print("Singleton works, both variables contain the same instance.") else: print("Singleton failed, variables contain different instances.") ``` -------------------------------- ### Shallow Copy Behavior Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Prototype/Conceptual/Output.txt Demonstrates how a shallow copy shares references to nested mutable objects. Modifying a nested object in the copy also modifies it in the original. ```python import copy class SomeCircularRef: def __init__(self, parent=None): self.parent = parent class Component: def __init__(self, name): self.name = name self.some_list_of_objects = [] self.some_circular_ref = SomeCircularRef(self) component = Component('Original') component.some_list_of_objects.append(1) shallow_copied_component = copy.copy(component) # Adding elements to shallow_copied_component's some_list_of_objects adds it to component's some_list_of_objects. shallow_copied_component.some_list_of_objects.append(2) print(f"Original list after shallow copy append: {component.some_list_of_objects}") # Changing objects in the component's some_list_of_objects changes that object in shallow_copied_component's some_list_of_objects. component.some_list_of_objects[0] = 100 print(f"Shallow copy list after original modification: {shallow_copied_component.some_list_of_objects}") # Changing the name attribute of the shallow copy does not affect the original shallow_copied_component.name = 'Shallow Copy' print(f"Original name: {component.name}") print(f"Shallow copy name: {shallow_copied_component.name}") ``` -------------------------------- ### Composite Pattern: Leaf Component Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Composite/Conceptual/Output.txt Represents a simple component in the composite structure. It cannot have children. ```python class Leaf: def __init__(self, name): self.name = name def operation(self): return self.name ``` -------------------------------- ### Composite Pattern: Composite Component Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Composite/Conceptual/Output.txt Represents a component that can contain other components (children). It implements operations by delegating to its children. ```python class Branch: def __init__(self, name): self.name = name self.children = [] def add(self, component): self.children.append(component) def operation(self): results = [self.name] for component in self.children: results.append(component.operation()) return "+".join(results) ``` -------------------------------- ### Deep Copy Behavior Source: https://github.com/refactoringguru/design-patterns-python/blob/main/src/Prototype/Conceptual/Output.txt Illustrates how a deep copy creates independent copies of nested mutable objects. Modifications to nested objects in the copy do not affect the original. ```python import copy class SomeCircularRef: def __init__(self, parent=None): self.parent = parent class Component: def __init__(self, name): self.name = name self.some_list_of_objects = [] self.some_circular_ref = SomeCircularRef(self) component = Component('Original') component.some_list_of_objects.append(1) deep_copied_component = copy.deepcopy(component) # Adding elements to deep_copied_component's some_list_of_objects doesn't add it to component's some_list_of_objects. deep_copied_component.some_list_of_objects.append(3) print(f"Original list after deep copy append: {component.some_list_of_objects}") print(f"Deep copy list after append: {deep_copied_component.some_list_of_objects}") # Changing objects in the component's some_list_of_objects doesn't change that object in deep_copied_component's some_list_of_objects. component.some_list_of_objects[0] = 1000 print(f"Original list after modification: {component.some_list_of_objects}") print(f"Deep copy list after original modification: {deep_copied_component.some_list_of_objects}") # Changing the name attribute of the deep copy does not affect the original deep_copied_component.name = 'Deep Copy' print(f"Original name: {component.name}") print(f"Deep copy name: {deep_copied_component.name}") # Demonstrating circular reference handling in deep copy print(f"ID of deep_copied_component.some_circular_ref.parent: {id(deep_copied_component.some_circular_ref.parent)}") print(f"ID of deep_copied_component.some_circular_ref.parent.some_circular_ref.parent: {id(deep_copied_component.some_circular_ref.parent.some_circular_ref.parent)}") # This shows that deepcopied objects contain same reference, they are not cloned repeatedly. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.