Can you name and describe the patterns from the GoF book that you have used in your work projects?
sobes.tech AI
Answer from AI
The book "Design Patterns: Elements of Reusable Object-Oriented Software" (GoF) describes 23 classic design patterns. In practical Python projects, the following are often used:
-
Singleton — ensures that a class has only one instance. In Python, it can be implemented via a module or a class with control over instance creation.
-
Factory Method — defines an interface for creating an object, allowing subclasses to alter the type of objects that will be created.
-
Observer — allows objects to subscribe to events of another object and receive notifications about changes.
-
Decorator — dynamically adds new responsibilities to objects by wrapping them.
Example of using the Singleton pattern in Python:
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
These patterns help write flexible and maintainable code.