91 lines
2.4 KiB
Python
91 lines
2.4 KiB
Python
"""
|
|
实例:
|
|
汤宝宝开了一家服装租赁店,好多客人来店里租衣服~
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
# 享元接口
|
|
class ClothingInterface(ABC):
|
|
@abstractmethod
|
|
def show(self):
|
|
pass
|
|
|
|
class Clothing(ClothingInterface):
|
|
"""享元对象 - 服装"""
|
|
|
|
style: str
|
|
size: str
|
|
color: str
|
|
|
|
def __init__(self, style: str, size: str, color: str):
|
|
self.style = style
|
|
self.size = size
|
|
self.color = color
|
|
|
|
def show(self):
|
|
print(f"服装款式: {self.style}, 尺码: {self.size}, 颜色: {self.color}")
|
|
|
|
|
|
class ClothingFactory:
|
|
"""享元工厂 - 服装店"""
|
|
|
|
_clothing_pool: dict[str, ClothingInterface]
|
|
|
|
def __init__(self):
|
|
self._clothing_pool = {}
|
|
|
|
def get_clothing(self, style: str, size: str, color: str) -> ClothingInterface:
|
|
key = f"{style}-{size}-{color}"
|
|
if key not in self._clothing_pool:
|
|
self._clothing_pool[key] = Clothing(style, size, color)
|
|
return self._clothing_pool[key]
|
|
|
|
def show_stock(self):
|
|
print("\n服装库存:")
|
|
for key, clothing in self._clothing_pool.items():
|
|
print(f"Keys: {key} -> ", end="")
|
|
clothing.show()
|
|
|
|
|
|
class Customer:
|
|
name: str
|
|
clothing: list[ClothingInterface]
|
|
|
|
def __init__(self, name: str):
|
|
self.name = name
|
|
self.clothing = []
|
|
|
|
def rent_clothing(self, clothing: ClothingInterface):
|
|
self.clothing.append(clothing)
|
|
print(f"{self.name} 租了一件服装: ", end="")
|
|
clothing.show()
|
|
|
|
def show_clothing(self):
|
|
print(f"\n客人{self.name} 租赁的服装有:")
|
|
for clothing in self.clothing:
|
|
clothing.show()
|
|
|
|
if __name__ == "__main__":
|
|
print("============= 享元模式 =============")
|
|
factory = ClothingFactory()
|
|
# 客人1租衣服
|
|
customer1 = Customer("小红")
|
|
customer1.rent_clothing(factory.get_clothing("连衣裙", "M", "红色"))
|
|
customer1.rent_clothing(factory.get_clothing("牛仔裤", "L", "蓝色"))
|
|
# 客人2租衣服
|
|
customer2 = Customer("小明")
|
|
customer2.rent_clothing(factory.get_clothing("连衣裙", "M", "红色"))
|
|
customer2.rent_clothing(factory.get_clothing("西裤", "S", "白色"))
|
|
|
|
print()
|
|
|
|
# 显示租赁情况
|
|
customer1.show_clothing()
|
|
customer2.show_clothing()
|
|
|
|
# 显示服装库存
|
|
factory.show_stock()
|
|
|
|
print("\n=========== 享元模式结束 ===========")
|