MST

星途 面试题库

面试题:Python替代switch case语句的设计模式及拓展应用

在大型项目中,使用Python替代switch case语句时,如何结合设计模式(如策略模式)来提高代码的可维护性、可扩展性和可读性?请详细阐述实现思路,并以一个具体的业务场景(例如电商系统中不同促销活动的计算逻辑)为例进行代码实现。
40.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 定义策略接口:创建一个抽象基类,定义每个具体策略需要实现的方法。在电商促销活动场景中,这个方法可以是计算促销后的价格。
  2. 创建具体策略类:针对每种促销活动,创建一个具体的策略类,继承自策略接口,并实现其中的方法。例如满减活动、折扣活动等。
  3. 使用字典映射:在Python中,可以使用字典来模拟switch case的功能,将促销活动类型作为键,对应的策略类实例作为值。这样可以通过键快速找到对应的策略实例。
  4. 调用策略:根据业务场景获取促销活动类型,从字典中获取对应的策略实例并调用其方法。

代码实现

from abc import ABC, abstractmethod


# 定义策略接口
class PromotionStrategy(ABC):
    @abstractmethod
    def calculate(self, price):
        pass


# 满减策略
class FullReductionStrategy(PromotionStrategy):
    def __init__(self, full_amount, reduction_amount):
        self.full_amount = full_amount
        self.reduction_amount = reduction_amount

    def calculate(self, price):
        if price >= self.full_amount:
            return price - self.reduction_amount
        return price


# 折扣策略
class DiscountStrategy(PromotionStrategy):
    def __init__(self, discount_rate):
        self.discount_rate = discount_rate

    def calculate(self, price):
        return price * self.discount_rate


# 策略工厂(使用字典映射)
class PromotionFactory:
    def __init__(self):
        self.promotion_map = {
            'full_reduction': FullReductionStrategy(200, 50),
            'discount': DiscountStrategy(0.8)
        }

    def get_promotion(self, promotion_type):
        return self.promotion_map.get(promotion_type)


# 电商系统中计算商品价格
def calculate_product_price(product_price, promotion_type):
    factory = PromotionFactory()
    strategy = factory.get_promotion(promotion_type)
    if strategy:
        return strategy.calculate(product_price)
    return product_price


# 示例调用
product_price = 300
promotion_type = 'full_reduction'
final_price = calculate_product_price(product_price, promotion_type)
print(f"商品原价: {product_price},促销后价格: {final_price}")

解释

  1. PromotionStrategy 是抽象基类,定义了 calculate 方法,所有具体策略类都要实现该方法。
  2. FullReductionStrategyDiscountStrategy 是具体策略类,分别实现满减和折扣的计算逻辑。
  3. PromotionFactory 使用字典 promotion_map 来映射促销活动类型和对应的策略实例。
  4. calculate_product_price 函数根据传入的促销活动类型从工厂获取策略实例并计算最终价格。通过这种方式,当需要新增促销活动时,只需添加新的具体策略类并在 PromotionFactory 中添加映射关系,无需修改大量现有代码,提高了代码的可维护性和可扩展性,同时代码结构清晰,提高了可读性。