Middle
204
What programming patterns do you know?
Answer from AI
sobes.tech AI
Known are creational, structural, and behavioral patterns.
Creational patterns:
- Factory Method: Provides an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created.
# Example of Factory Method class Creator: def factory_method(self): raise NotImplementedError() def some_operation(self): product = self.factory_method() return f"Creator: The same creator's code has just worked with {product.operation()}" class ConcreteCreator1(Creator): def factory_method(self): return ConcreteProduct1() class ConcreteProduct1: def operation(self): return "{Result of the ConcreteProduct1}" - Abstract Factory: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
- Singleton: Ensures a class has only one instance and provides a global point of access to it.
# Example of Singleton class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance return cls._instances[cls] class Singleton(metaclass=SingletonMeta): pass - Builder: Allows step-by-step construction of complex objects, separating the construction process from its representation.
- Prototype: Enables creating copies of existing objects without delving into their implementation details.
Structural patterns:
- Adapter: Allows objects with incompatible interfaces to work together.
# Example of Adapter class Target: def request(self): return "Target: The default target's behavior." class Adaptee: def specific_request(self): return ".eetpadA eht fo roivaheb laicepS" class Adapter(Target, Adaptee): def request(self): return f"Adapter: (TRANSLATED) {self.specific_request()[::-1]}" - Bridge: Decouples an abstraction from its implementation so that the two can vary independently.
- Composite: Composes objects into tree structures to represent hierarchies.
- Decorator: Adds responsibilities to objects dynamically.
- Facade: Provides a unified interface to a set of interfaces in a subsystem.
- Flyweight: Uses sharing to support large numbers of fine-grained objects efficiently.
- Proxy: Provides a surrogate or placeholder for another object to control access to it.
Behavioral patterns:
- Chain of Responsibility: Passes requests along a chain of handlers.
- Command: Encapsulates a request as an object, allowing parameterization of clients with different requests, queuing or logging requests, and supporting undo operations.
# Example of Command class Command: def execute(self): pass class SimpleCommand(Command): def __init__(self, payload): self._payload = payload def execute(self): print(f"SimpleCommand: See, I can do simple things like printing ({self._payload})") class Invoker: _on_start = None _on_finish = None def set_on_start(self, command): self._on_start = command def set_on_finish(self, command): self._on_finish = command def do_something_important(self): if isinstance(self._on_start, Command): self._on_start.execute() print("Invoker: Doing something really important.") if isinstance(self._on_finish, Command): self._on_finish.execute() - Iterator: Provides a way to access the elements of a collection sequentially without exposing its underlying representation.
- Mediator: Defines an object that encapsulates how a set of objects interact.
- Memento: Allows capturing and restoring an object's internal state without violating encapsulation.
- Observer: Defines a dependency between objects so that when one object changes its state, all its dependents are notified and updated automatically.
- State: Allows an object to alter its behavior when its internal state changes.
- Strategy: Encapsulates algorithms within a family, making them interchangeable.
# Example of Strategy class Strategy: def do_algorithm(self, data): pass class ConcreteStrategyA(Strategy): def do_algorithm(self, data): return sorted(data) class Context: def __init__(self, strategy): self._strategy = strategy def set_strategy(self, strategy): self._strategy = strategy def do_some_business_logic(self): data = ["a", "b", "c", "d", "e"] result = self._strategy.do_algorithm(data) print(",".join(result)) - Template Method: Defines the skeleton of an algorithm in a base class but lets subclasses override specific steps without changing the algorithm's structure.
- Visitor: Adds new operations to existing object structures without modifying those structures.
There are also more specific patterns like Model-View-Controller (MVC), Model-View-Presenter (MVP), Model-View-ViewModel (MVVM), and other architectural patterns.