重温设计模式 --- 策略模式

引言

策略模式是一种行为设计模式,它允许在运行时选择算法的行为。该模式定义了一系列算法,将它们封装成独立的类,并使它们可以互相替换。这使得算法可以独立于使用它们的客户端而变化。

在策略模式中,有三个主要的角色:

  • 环境(Context):它是使用策略的对象,它维护一个对策略对象的引用,并将客户端请求委托给该对象执行。
  • 抽象策略(Strategy):它定义了所有具体策略所遵循的接口,通常由一个抽象类或者接口实现。
  • 具体策略(Concrete Strategy):它实现了抽象策略中定义的接口,提供了算法的具体实现。

接下里使用c#创建一个购物车,为产品计算不同的折扣:

抽象策略类

// 抽象策略类
public abstract class DiscountStrategy
{
    public abstract decimal CalculateDiscount(decimal price);
}

具体策略类

public class ChristmasDiscount : DiscountStrategy
{
    public override decimal CalculateDiscount(decimal price)
    {
        return price * 0.3m;
    }
}

public class SpringFestivalDiscount : DiscountStrategy
{
    public override decimal CalculateDiscount(decimal price)
    {
        return price * 0.5m;
    }
}

环境类

public class ShoppingCart
{
    private DiscountStrategy discountStrategy;

    public ShoppingCart(DiscountStrategy discountStrategy)
    {
        this.discountStrategy = discountStrategy;
    }

    public decimal CalculateTotalPrice(decimal price)
    {
        return price - this.discountStrategy.CalculateDiscount(price);
    }
}

上文例子中,我们定义了一个抽象策略类DiscountStrategy,它定义了一个CalculateDiscount方法。然后我们定义了两个具体策略类ChristmasDiscountSpringFestivalDiscount,它们分别实现了CalculateDiscount方法以提供具体的折扣计算逻辑。

最后,我们定义了一个环境类ShoppingCart,它持有一个DiscountStrategy对象,并在计算购物车中物品的总价时,使用持有的DiscountStrategy对象来计算折扣。客户端可以在运行时选择不同的具体策略对象作为DiscountStrategy,以便在计算购物车物品总价时选择不同的折扣算法。

接下假设有一个Prada包的价格是12000,可以分别计算一下圣诞节折扣价和春节折扣价:

decimal pradaBag = 12000;
DiscountStrategy christmasDiscount = new ChristmasDiscount();
DiscountStrategy springFestivalDiscount = new SpringFestivalDiscount();

ShoppingCart christmasShoppingCart = new ShoppingCart(christmasDiscount);
ShoppingCart springFestivalShoppingCart = new ShoppingCart(springFestivalDiscount);

var discountedPrice = christmasShoppingCart.CalculateTotalPrice(pradaBag);
Console.WriteLine("Prada bag christmas discount price is " + discountedPrice);

discountedPrice = springFestivalShoppingCart.CalculateTotalPrice(pradaBag);
Console.WriteLine("Prada bag  Spring Festival discount price is " + discountedPrice);

输出:

Prada bag christmas discount price is 8400.0
Prada bag  Spring Festival discount price is 6000.0

结论

策略模式的核心是抽象策略类和具体策略类。抽象策略类定义了一个接口或抽象类,具体策略类实现了这个接口或抽象类,并实现了具体的算法或行为。在使用策略模式时,我们首先创建一个策略接口或抽象类,然后定义多个具体策略类实现这个接口或抽象类。

在程序运行时,我们可以动态地切换不同的具体策略类,从而实现不同的算法或行为。这种灵活性使得策略模式非常适合那些需要在运行时根据不同条件选择不同算法的场合。

posted @ 2023-07-12 08:18  NiueryDiary  阅读(19)  评论(0编辑  收藏  举报