策略模式是一种行为型设计模式,它定义了一系列算法,将每个算法封装到独立的类中,并让它们可以相互替换。策略模式让算法的变化独立于使用算法的客户端,从而实现了算法的复用和扩展。
策略模式的核心思想是将算法的实现和使用分离,将算法的实现交给独立的策略类来完成,而将算法的选择和调用交给客户端来完成。客户端可以根据需要选择不同的策略类,从而达到不同的算法效果。
下面是一个简单的策略模式的Demo,假设有一个商场要对不同的VIP用户提供不同的折扣,例如普通VIP用户享受95折优惠,金牌VIP用户享受85折优惠,钻石VIP用户享受75折优惠等。
python
Copy
折扣策略接口
class DiscountStrategy:
def get_discount(self, price):
pass
普通VIP用户折扣策略类
class NormalVipDiscount(DiscountStrategy):
def get_discount(self, price):
return price * 0.95
金牌VIP用户折扣策略类
class GoldVipDiscount(DiscountStrategy):
def get_discount(self, price):
return price * 0.85
钻石VIP用户折扣策略类
class DiamondVipDiscount(DiscountStrategy):
def get_discount(self, price):
return price * 0.75
商场类
class Mall:
def init(self, discount_strategy):
self.discount_strategy = discount_strategy
def calculate_discount(self, price):
return self.discount_strategy.get_discount(price)
客户端代码
normal_vip_discount = NormalVipDiscount()
gold_vip_discount = GoldVipDiscount()
diamond_vip_discount = DiamondVipDiscount()
mall = Mall(normal_vip_discount)
price = 100
discount_price = mall.calculate_discount(price)
print(f"普通VIP用户消费{price}元,享受95折优惠,折后价格为{discount_price}元。")
mall = Mall(gold_vip_discount)
discount_price = mall.calculate_discount(price)
print(f"金牌VIP用户消费{price}元,享受85折优惠,折后价格为{discount_price}元。")
mall = Mall(diamond_vip_discount)
discount_price = mall.calculate_discount(price)
print(f"钻石VIP用户消费{price}元,享受75折优惠,折后价格为{discount_price}元。")
这个Demo中,DiscountStrategy是折扣策略接口,定义了一个get_discount方法,用于计算折扣金额。NormalVipDiscount、GoldVipDiscount和DiamondVipDiscount是具体的折扣策略类,它们分别实现了get_discount方法,完成了不同的折扣计算逻辑。Mall是商场类,它接受一个DiscountStrategy对象作为参数,根据传入的折扣策略对象,计算出具体的折扣金额。
当客户端使用策略模式时,需要先定义一个抽象的策略接口,然后实现具体的策略类,每个策略类都封装了一种算法,用于计算具体的结果。在客户端中,需要将具体的策略对象传递给调用者,让调用者根据具体的策略对象来完成不同的算法执行。通过策略模式,可以实现算法的复用和扩展,同时也保证了算法的独立性和可维护性。
以下是一些推荐的学习资料和链接,可以帮助你更好地学习策略模式:
《Head First 设计模式》:这是一本非常通俗易懂的设计模式入门书籍,其中包含了对策略模式的讲解和示例代码。
《设计模式:可复用面向对象软件的基础》:这是设计模式的经典著作之一,其中包含了对策略模式的详细讲解和示例代码。
《图解设计模式:以UML为基础,学习23种设计模式》:这是一本以图解为主的设计模式入门书籍,其中包含了对策略模式的详细讲解和示例代码。
策略模式的Java实现:这是一个包含了策略模式示例代码的Java项目,可以帮助读者更好地理解和应用策略模式。
GitHub链接:https://github.com/iluwatar/java-design-patterns/tree/master/strategy ↗
总之,学习策略模式需要结合书籍和实践,建议读者选择一些适合自己的入门书籍,同时结合实际项目中的设计问题进行实践,加深对策略模式的理解和应用。