MST

星途 面试题库

面试题:Python字典在复杂场景下存储类似对象的设计模式应用

在一个大型项目中,需要使用Python字典存储不同类型但有部分相似属性的对象,比如有员工类、客户类、合作伙伴类,它们都有ID、名称属性,但各自还有特有的属性。要求设计一个通用的字典存储方案,能够高效地进行对象的增删改查操作,同时满足扩展性需求,方便后续增加新类型的类似对象。请阐述设计思路,包括可能用到的设计模式(如工厂模式、策略模式等),并给出关键代码示例及对其原理的详细解释。
46.8万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 抽象基类:定义一个抽象基类,包含所有类共有的属性(如ID和名称),这样可以确保所有具体类都有这些基本属性,便于在字典中统一管理。
  2. 工厂模式:使用工厂模式来创建不同类型的对象。这使得对象的创建逻辑与使用逻辑分离,便于代码的维护和扩展。当需要增加新类型的对象时,只需在工厂类中添加相应的创建逻辑。
  3. 字典结构:使用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

原理详细解释

  1. 抽象基类BaseEntity:它定义了所有具体类共有的idname属性,通过继承这个抽象基类,EmployeeCustomerPartner类都自动拥有了这些属性。
  2. 具体类(EmployeeCustomerPartner:这些类继承自BaseEntity,并在初始化时调用父类的构造函数,以确保idname属性的正确设置。同时,它们各自拥有特有的属性。
  3. 工厂类EntityFactorycreate_entity方法根据传入的entity_type来创建不同类型的对象。这种方式将对象的创建逻辑集中在一个地方,方便管理和扩展。例如,如果要增加新类型的对象,只需在create_entity方法中添加新的判断逻辑。
  4. 字典操作函数(add_entityremove_entityupdate_entityfind_entity:这些函数利用Python字典以id作为键的特性,实现了高效的增删改查操作。add_entity将对象添加到字典中,remove_entity根据id删除对象,update_entity根据id更新对象,find_entity根据id查找对象。这种设计模式和字典存储方案不仅满足了高效操作的需求,还具备良好的扩展性,便于后续增加新类型的类似对象。