什么是设计模式
设计模式是软件开发中用来解决常见问题的模板或指导原则,它们是经过验证的、可重用的解决方案。其中,策略模式和工厂模式是两种非常重要的设计模式,各自有着特定的含义和应用场景:
什么是策略模式
策略模式(Strategy Pattern)
含义:策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互相替换。策略让算法的变化独立于使用算法的客户。它主要关注的是行为的多变性,允许在运行时根据需要选择算法或行为。
核心组件:
Context(上下文):使用策略的对象,它定义了策略接口并维护一个对策略对象的引用。
Strategy(策略):定义了一个操作的一组算法,封装这些算法,并使它们可以相互替换。策略类通常由多个实现同一抽象接口的类组成。
Concrete Strategies(具体策略):实现了策略接口的具体算法类,提供了不同的实现方式。
应用场景:当有多种算法或行为可以互换使用时,如不同的排序算法、支付方式选择等。
### 以下说明是借用流畅的python中的一个例子:
from abc import ABC, abstractmethod
from collections import namedtuple
Customer = namedtuple('Customer', 'name fidelity')
class LineItem:
"""单个商品信息"""
def __init__(self, product, quantity, price):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
class Order: # 上下文
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self):
# 总价
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self):
# 打折后价格
if self.promotion is None:
discount = 0
else:
discount = self.promotion.discount(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
class Promotion(ABC): # 策略: 抽象基类
@abstractmethod
def discount(self, order):
"""返回折扣金额(正值) """
class FidelityPromo(Promotion): # 第一个具体策略
"""为积分为1000或以上的顾客提供5%折扣"""
def discount(self, order):
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
class BulkItemPromo(Promotion): # 第二个具体策略
"""单个商品为20个或以上时提供10%折扣"""
def discount(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
class LargeOrderPromo(Promotion): # 第三个具体策略
"""订单中的不同商品达到10个或以上时提供7%折扣"""
def discount(self, order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
什么是工厂模式
工厂模式(Factory Pattern)
含义:工厂模式提供了一种创建对象的最佳方式,它通过专门的工厂类来负责创建其他类的实例,而不指定具体的产品类。工厂模式主要关注的是对象的创建过程,尤其是当创建过程复杂时,它能够将对象的创建逻辑与使用逻辑分离。
类型:
简单工厂模式:提供一个创建对象的静态方法,决定实例化哪一个类,但这个模式破坏了“开闭原则”。
工厂方法模式:定义一个创建对象的接口,但让子类决定实例化哪一个类。工厂方法让类的实例化推迟到子类。
抽象工厂模式:提供一个接口用于创建一系列相关或相互依赖的对象,而无需指定它们具体的类。
应用场景:当系统不应该知道它所创建的对象的具体类时,或者当一个类希望由其子类来指定它所创建的对象时。
区别
策略模式关注于行为的多样性和可替换性,强调算法的独立性和上下文中的使用。
工厂模式关注于对象的创建过程,确保创建过程的灵活性和封装性,不关心行为的多样性。
这两种模式虽然都属于设计模式,但解决的问题领域不同,策略模式更侧重于行为的灵活选择,而工厂模式则侧重于对象创建的灵活性和解耦。