INTRO:
Types of design patterns:
- Creational Patterns (deals with object creation mechanisms)
- Singleton, Factory, Builder
- Structural Patterns (deals with object composition and structure)
- Behavioral Patterns (deals with object communication and responsibility)
- Observer, Strategy, Command
Python-specific design patterns:
- Decorator, Iterator, Context manager
The most popular design patterns in Python:
- Singleton (configuration or connections management)
- Factory (objects are created dynamically)
- Adapter (library integrations)
- Observer (notifications, events)
- Facade (complex API simplifying)
- Decorator (extending functionalities in runtime)
- Builder (more complex objects)
- Proxy (lazy-loading, remote calls)
- Command (task queues)
REVIEWING DESIGN PATTERNS:
Composition:
- Composition is a design principle in object-oriented programming where one class is composed of one or more objects from other classes.
- Composition is favored over inheritance when a "has-a" relationship makes more sense than an "is-a" relationship.
- Example
Strategy:
- It allows you to define different ways of doing something (strategies) and let the client choose which one to use at runtime.
- It is similar to Adapter because both plays as Proxy-Agent separating Client logic from detailed implementation. However, Strategy and Adapter in general have different goals.
- Strategy example
- Strategy design pattern consists of:
- Context - the class using the algorithm, but doesnt know how is implemented
- Strategy Interface - common interface for all Strategies that Context uses
- Concrete Strategies - specific Strategy implementations
Observer:
- it is for creating One-to-Many dependency between objects
- when one object (Subject) changes own state then all dependant objects (Observers) are automatically notified and can update appropriately
Decorator:
Adapter:
- Adapter example
- Adapter design pattern is component translating things between incompatible interfaces
- It uses composition and activity delegation to achieve these goals
Singleton:
- It ensures that a class has only one instance and provides a global access point to that instance. It is used to manage a shared resource or state across the system, preventing the creation of multiple instances of the same class. Singleton is sometimes called anti-pattern. Whether it's beneficial or problematic depends on how and why it's used.
- Typical Use cases:
- Key characteristics of the Singleton Pattern:
- Single Instance, Global Access, Lazy Initialization, Controlled Access