策略模式通过定义统一接口封装多种算法,使算法可互换且易于扩展。首先定义IPaymentStrategy接口声明Pay方法;接着实现AlipayStrategy和WeChatPayStrategy类提供具体支付逻辑;再创建PaymentContext类持有策略接口,通过构造函数或SetStrategy方法动态设置策略;客户端在Main中创建上下文并执行支付,输出分别为“使用支付宝支付 ¥299.99 元”和“使用微信支付 ¥188.00 元”。新增支付方式只需添加新类实现接口,无需修改现有代码,符合开闭原则。

策略模式是一种行为设计模式,它让你定义一系列算法或行为,并将它们封装在独立的类中,使它们可以互相替换。C# 中通过接口和多态特性能很好地实现策略模式。
首先创建一个策略接口,声明所有支持的算法共有的操作:
public interface IPaymentStrategy
{
void Pay(double amount);
}
public class AlipayStrategy : IPaymentStrategy
{
public void Pay(double amount)
{
Console.WriteLine($"使用支付宝支付 {amount:C} 元");
}
}
<p>public class WeChatPayStrategy : IPaymentStrategy
{
public void Pay(double amount)
{
Console.WriteLine($"使用微信支付 {amount:C} 元");
}
}
</font></p><H3>上下文类使用策略</H3><p>创建一个上下文类来接收并执行策略,客户端可根据需要动态切换:</p><font face="Courier New"><pre class="brush:php;toolbar:false;">
public class PaymentContext
{
private IPaymentStrategy _strategy;
<pre class='brush:php;toolbar:false;'>public PaymentContext(IPaymentStrategy strategy)
{
_strategy = strategy;
}
public void SetStrategy(IPaymentStrategy strategy)
{
_strategy = strategy;
}
public void ExecutePayment(double amount)
{
_strategy.Pay(amount);
}}
在 Main 方法中演示如何使用不同的支付策略:
class Program
{
static void Main(string[] args)
{
var context = new PaymentContext(new AlipayStrategy());
context.ExecutePayment(299.99);
<pre class='brush:php;toolbar:false;'> // 切换为微信支付
context.SetStrategy(new WeChatPayStrategy());
context.ExecutePayment(188.00);
}}
输出结果:
使用支付宝支付 ¥299.99 元 使用微信支付 ¥188.00 元
通过这种方式,新增支付方式时只需添加新的策略类并实现接口,无需修改原有代码,符合开闭原则。基本上就这些,不复杂但容易忽略细节。
以上就是C#怎么实现策略模式 C#设计模式之策略模式代码示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号