certain-design-patterns/flyweight.py

35 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from abc import ABC, abstractmethod
class Flyweight(ABC):
"""Абстрактный класс Легковеса."""
@abstractmethod
def operation(self, extrinsic_state): pass
"""Конкретный Легковес, который хранит внутреннее состояние."""
class ConcreteFlyweight(Flyweight):
def __init__(self, intrinsic_state): self.intrinsic_state = intrinsic_state
def operation(self, extrinsic_state):
return f"Легковес с внутренним состоянием: {self.intrinsic_state}, и адресом: {extrinsic_state}"
class FlyweightFactory:
"""Фабрика Легковесов, которая управляет созданием и хранением Легковесов."""
def __init__(self): self._flyweights = {}
def get_flyweight(self, intrinsic_state):
if intrinsic_state not in self._flyweights:
self._flyweights[intrinsic_state] = ConcreteFlyweight(intrinsic_state)
return self._flyweights[intrinsic_state]
factory = FlyweightFactory()
# Создаем легковесы
flyweights = [
factory.get_flyweight("A"),
factory.get_flyweight("B"),
factory.get_flyweight("A"), # Этот легковес будет переиспользован
factory.get_flyweight("C"),
]
# Выполняем операции с легковесами
for i, flyweight in enumerate(flyweights):
print(flyweight.operation(f"{flyweight}"))