设计思路
- 抽象基类:定义一个抽象基类,包含所有类共有的属性(如ID和名称),这样可以确保所有具体类都有这些基本属性,便于在字典中统一管理。
- 工厂模式:使用工厂模式来创建不同类型的对象。这使得对象的创建逻辑与使用逻辑分离,便于代码的维护和扩展。当需要增加新类型的对象时,只需在工厂类中添加相应的创建逻辑。
- 字典结构:使用Python字典存储对象,以对象的ID作为键,这样可以保证对象的唯一性,并且能够高效地进行查找、删除和修改操作。
关键代码示例
from abc import ABC, abstractmethod
# 抽象基类
class BaseEntity(ABC):
def __init__(self, id, name):
self.id = id
self.name = name
# 员工类
class Employee(BaseEntity):
def __init__(self, id, name, department):
super().__init__(id, name)
self.department = department
# 客户类
class Customer(BaseEntity):
def __init__(self, id, name, purchase_history):
super().__init__(id, name)
self.purchase_history = purchase_history
# 合作伙伴类
class Partner(BaseEntity):
def __init__(self, id, name, cooperation_type):
super().__init__(id, name)
self.cooperation_type = cooperation_type
# 工厂类
class EntityFactory:
@staticmethod
def create_entity(entity_type, id, name, **kwargs):
if entity_type == 'employee':
return Employee(id, name, kwargs.get('department'))
elif entity_type == 'customer':
return Customer(id, name, kwargs.get('purchase_history'))
elif entity_type == 'partner':
return Partner(id, name, kwargs.get('cooperation_type'))
else:
raise ValueError('Unsupported entity type')
# 字典存储
entity_dict = {}
# 添加对象
def add_entity(entity):
entity_dict[entity.id] = entity
# 删除对象
def remove_entity(id):
if id in entity_dict:
del entity_dict[id]
# 修改对象
def update_entity(id, new_entity):
if id in entity_dict:
entity_dict[id] = new_entity
# 查找对象
def find_entity(id):
return entity_dict.get(id)
# 使用示例
factory = EntityFactory()
employee = factory.create_entity('employee', 1, 'John', department='HR')
customer = factory.create_entity('customer', 2, 'Alice', purchase_history=[])
partner = factory.create_entity('partner', 3, 'Bob', cooperation_type='joint venture')
add_entity(employee)
add_entity(customer)
add_entity(partner)
print(find_entity(1).name) # 输出 John
update_entity(1, factory.create_entity('employee', 1, 'Jane', department='Finance'))
print(find_entity(1).name) # 输出 Jane
remove_entity(1)
print(find_entity(1)) # 输出 None
原理详细解释
- 抽象基类
BaseEntity
:它定义了所有具体类共有的id
和name
属性,通过继承这个抽象基类,Employee
、Customer
和Partner
类都自动拥有了这些属性。
- 具体类(
Employee
、Customer
、Partner
):这些类继承自BaseEntity
,并在初始化时调用父类的构造函数,以确保id
和name
属性的正确设置。同时,它们各自拥有特有的属性。
- 工厂类
EntityFactory
:create_entity
方法根据传入的entity_type
来创建不同类型的对象。这种方式将对象的创建逻辑集中在一个地方,方便管理和扩展。例如,如果要增加新类型的对象,只需在create_entity
方法中添加新的判断逻辑。
- 字典操作函数(
add_entity
、remove_entity
、update_entity
、find_entity
):这些函数利用Python字典以id
作为键的特性,实现了高效的增删改查操作。add_entity
将对象添加到字典中,remove_entity
根据id
删除对象,update_entity
根据id
更新对象,find_entity
根据id
查找对象。这种设计模式和字典存储方案不仅满足了高效操作的需求,还具备良好的扩展性,便于后续增加新类型的类似对象。