Middle
Have you used design patterns (facade, strategy, etc.)? Provide an example.
sobes.tech AI
Answer from AI
Yes, I have used various design patterns in Python. For example, the Facade pattern helps simplify interaction with a complex subsystem by providing a simple interface.
An example of a facade for working with a database and caching:
class Database:
def query(self, sql):
print(f"Executing query: {sql}")
return "data from DB"
class Cache:
def get(self, key):
print(f"Getting from cache: {key}")
return None
def set(self, key, value):
print(f"Setting cache: {key} = {value}")
class DataFacade:
def __init__(self):
self.db = Database()
self.cache = Cache()
def get_data(self, key):
data = self.cache.get(key)
if data is None:
data = self.db.query(f"SELECT * FROM table WHERE key = '{key}'")
self.cache.set(key, data)
return data
# Usage
facade = DataFacade()
result = facade.get_data('user123')
The Strategy pattern allows changing the behavior algorithms of an object at runtime. For example, choosing a sorting method:
from abc import ABC, abstractmethod
class SortStrategy(ABC):
@abstractmethod
def sort(self, data):
pass
class BubbleSort(SortStrategy):
def sort(self, data):
print("Bubble sort")
# implementation of bubble sort
return sorted(data) # for example
class QuickSort(SortStrategy):
def sort(self, data):
print("Quick sort")
# implementation of quick sort
return sorted(data) # for example
class Sorter:
def __init__(self, strategy: SortStrategy):
self.strategy = strategy
def sort(self, data):
return self.strategy.sort(data)
# Usage
sorter = Sorter(BubbleSort())
sorted_data = sorter.sort([5, 3, 6, 2])
sorter.strategy = QuickSort()
sorted_data = sorter.sort([5, 3, 6, 2])
These patterns help make the code more flexible and maintainable.