C#中的策略模式

策略模式:动态切换算法

当业务需要支持多种算法变体时,常见做法:

1
2
if(paymentMethod == "Cash") ProcessCash();
else if(paymentMethod == "CreditCard") ProcessCreditCard();

但是这样容易出现一些问题:

  1. 新增支付方式需修改核心代码

  2. 支付逻辑与控制器耦合

  3. 难以单独测试支付算法

解决方案:策略模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
///<策略模式>
public interface IPaymentStrategy
{
void ProcessPayment();
}


public class CashPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment()
{
Console.WriteLine("Processing cash payment");
}
}

public class CreditCardPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment()
{
Console.WriteLine("Processing credit card payment");
}
}

public class PaymentProcessor
{
public void ProcessPayment(IPaymentStrategy paymentStrategy)
{
paymentStrategy.ProcessPayment();
}
}

///<策略模式/>

设计原则

  1. 开闭原则

    • 添加新支付方式只需创建新类

    • 示例:添加PayPalStrategy无需修改处理器

1
2
3
4
5
6
7
public class PayPalStrategy : IPaymentStrategy
{
public void ProcessPayment()
{
Console.WriteLine("Processing PayPal payment");
}
}
  1. 组合优于继承

    1
    2
    3
    4
    5
    6
    7
    public class PaymentProcessor
    {
    public void ProcessPayment(IPaymentStrategy paymentStrategy)
    {
    paymentStrategy.ProcessPayment();
    }
    }
  2. 单一职责原则

    • 每种策略只负责一种算法实现

    • 控制器只负责执行策略

适用场景
- 需要在运行时切换算法

- 有多个相似类仅在行为上不同

- 需要隔离复杂算法实现细节

典型应用
- 支付方式处理

- 数据压缩算法

- 导航路径计算

- 折扣计算规则

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
///<策略模式>
public interface IPaymentStrategy
{
void ProcessPayment();
}


public class CashPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment()
{
Console.WriteLine("Processing cash payment");
}
}

public class CreditCardPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment()
{
Console.WriteLine("Processing credit card payment");
}
}

public class PaymentProcessor
{
public void ProcessPayment(IPaymentStrategy paymentStrategy)
{
paymentStrategy.ProcessPayment();
}
}

///<策略模式/>
public class Program
{
public static void Main(string[] args)
{
///<策略模式>
Console.WriteLine();
Console.WriteLine("策略模式:");
PaymentProcessor paymentProcessor = new PaymentProcessor();
paymentProcessor.ProcessPayment(new CashPaymentStrategy());
paymentProcessor.ProcessPayment(new CreditCardPaymentStrategy());
///<策略模式/>
}
}