重构享元模式示例,统一服装接口类型,增强代码一致性和可读性

This commit is contained in:
2026-01-02 17:26:52 +08:00
parent 4589debb92
commit 232b926a97
3 changed files with 33 additions and 16 deletions
+12 -5
View File
@@ -3,8 +3,15 @@
汤宝宝开了一家服装租赁店,好多客人来店里租衣服~
"""
from abc import ABC, abstractmethod
class Clothing:
# 享元接口
class ClothingInterface(ABC):
@abstractmethod
def show(self):
pass
class Clothing(ClothingInterface):
"""享元对象 - 服装"""
style: str
@@ -23,12 +30,12 @@ class Clothing:
class ClothingFactory:
"""享元工厂 - 服装店"""
_clothing_pool: dict[str, Clothing]
_clothing_pool: dict[str, ClothingInterface]
def __init__(self):
self._clothing_pool = {}
def get_clothing(self, style: str, size: str, color: str) -> Clothing:
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)
@@ -43,13 +50,13 @@ class ClothingFactory:
class Customer:
name: str
clothing: list[Clothing]
clothing: list[ClothingInterface]
def __init__(self, name: str):
self.name = name
self.clothing = []
def rent_clothing(self, clothing: Clothing):
def rent_clothing(self, clothing: ClothingInterface):
self.clothing.append(clothing)
print(f"{self.name} 租了一件服装: ", end="")
clothing.show()