目的和问题解决方式:
参与者:
关注点:
适用场景:
总的来说,策略模式用于选择不同的策略或算法,而责任链模式用于将请求传递给一系列对象,直到找到一个合适的处理者。它们解决不同类型的问题,根据具体情况选择合适的模式来实现更清晰和可维护的代码。
我们通过具体的示例来说明策略模式和责任链模式的区别。
假设你正在开发一个电商网站,需要计算商品的折扣价格。不同类型的商品可以有不同的折扣策略,例如普通商品按原价销售,VIP用户享受9折优惠,促销商品打7折,以及其他可能的折扣策略。
- # 抽象策略接口
- class DiscountStrategy:
- def apply_discount(self, original_price):
- pass
-
- # 具体策略类
- class RegularCustomerDiscount(DiscountStrategy):
- def apply_discount(self, original_price):
- return original_price
-
- class VipCustomerDiscount(DiscountStrategy):
- def apply_discount(self, original_price):
- return original_price * 0.9
-
- class SaleDiscount(DiscountStrategy):
- def apply_discount(self, original_price):
- return original_price * 0.7
-
- # 上下文类
- class ShoppingCart:
- def __init__(self, discount_strategy):
- self.discount_strategy = discount_strategy
- def checkout(self, cart_total):
- return self.discount_strategy.apply_discount(cart_total)
- # 客户端代码
- cart_total = 100.0
- regular_customer = ShoppingCart(RegularCustomerDiscount())
- vip_customer = ShoppingCart(VipCustomerDiscount())
- sale = ShoppingCart(SaleDiscount())
-
- print("Regular customer total:", regular_customer.checkout(cart_total))
- print("VIP customer total:", vip_customer.checkout(cart_total))
- print("Sale total:", sale.checkout(cart_total))
在这个例子中,策略模式允许你在运行时选择不同的折扣策略,而不需要修改购物车类。
现在,假设你的电商网站需要一个日志记录系统,可以根据不同的日志级别将日志消息传递给不同的日志处理器。日志级别包括DEBUG、INFO、WARNING和ERROR,每个级别都有不同的处理方式,例如将DEBUG级别的日志保存到文件,将ERROR级别的日志发送给管理员。
- # 抽象处理器接口
- class Logger:
- def set_next(self, next_logger):
- pass
-
- def log_message(self, level, message):
- pass
-
- # 具体处理器类
- class DebugLogger(Logger):
- def set_next(self, next_logger):
- self.next_logger = next_logger
- def log_message(self, level, message):
- if level == "DEBUG":
- print(f"Debug Log: {message}")
- elif self.next_logger:
- self.next_logger.log_message(level, message)
-
- class InfoLogger(Logger):
- def set_next(self, next_logger):
- self.next_logger = next_logger
- def log_message(self, level, message):
- if level == "INFO":
- print(f"Info Log: {message}")
- elif self.next_logger:
- self.next_logger.log_message(level, message)
-
- class ErrorLogger(Logger):
- def set_next(self, next_logger):
- self.next_logger = next_logger
- def log_message(self, level, message):
- if level == "ERROR":
- print(f"Error Log: {message}")
- elif self.next_logger:
- self.next_logger.log_message(level, message)
-
- # 客户端代码
- debug_logger = DebugLogger()
- info_logger = InfoLogger()
- error_logger = ErrorLogger()
-
- debug_logger.set_next(info_logger)
- info_logger.set_next(error_logger)
-
- debug_logger.log_message("DEBUG", "This is a debug message.")
- debug_logger.log_message("INFO", "This is an info message.")
- debug_logger.log_message("ERROR", "This is an error message.")
在这个例子中,责任链模式允许你将日志消息传递给一系列不同的日志处理器,每个处理器决定是否处理消息,以及如何处理。如果某个处理器无法处理消息,它将消息传递给下一个处理器,直到找到合适的处理者。这种方式可以实现灵活的日志记录系统,而不需要修改已有的代码。
总结:策略模式用于选择不同的策略来处理不同的情况,而责任链模式用于将请求传递给一系列处理器,直到找到一个合适的处理者,有点像击鼓传花。