策略模式是一种行为设计模式,它允许您定义一系列算法,封装每个算法并使它们可互换。此模式在需要在运行时切换不同算法的情况下特别有用。在本文中,我们将探讨如何使用具有依赖项注入的最小 API 在.NET中实现策略模式。
一. 实时支付处理系统示例
我们将创建一个支持多种付款方式的 Web API:微信、支付定、信用卡。我们将使用策略模式封装每种付款方式并在它们之间动态切换。
二. 逐步实现
1. 定义策略接口
创建一个接口IPaymentStrategy,声明一个方法ProcessPayment(decimal amount)来标准化支付处理逻辑。
public interface IPaymentStrategy
{
void ProcessPayment(decimal amount);
}
2. 实施具体策略
在 WeiXinPaymentStrategy、AliPaymentStrategy和CreditCardPaymentStrategy等类中实现 IPaymentStrategy 接口,每个类都提供处理付款的特定逻辑。
public class WenXinPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
// 微信支付逻辑
Console.WriteLine($"微信支付{amount:C}");
}
}
public class AliPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
// 支付宝支付逻辑
Console.WriteLine($"支付宝支付{amount:C}");
}
}
public class CreditCardPaymentStrategy : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
// 信用卡支付逻辑
Console.WriteLine($"信用卡支付 {amount:C}");
}
}
3. 为上下文创建接口
定义一个接口IPaymentContext,声明方法SetPaymentStrategy(IPaymentStrategy paymentStrategy)和ExecutePayment(decimal amount)来管理和执行所选的支付策略。
public interface IPaymentContext
{
void SetPaymentStrategy(IPaymentStrategy paymentStrategy);
void ExecutePayment(decimal amount);
}
4.实现 PaymentContext 类
在PaymentContext类中实现IPaymentContext接口,存储当前的支付策略并调用其ProcessPayment方法。
public class PaymentContext : IPaymentContext
{
private IPaymentStrategy _paymentStrategy;
public void SetPaymentStrategy(IPaymentStrategy paymentStrategy)
{
_paymentStrategy = paymentStrategy;
}
public void ExecutePayment(decimal amount)
{
_paymentStrategy.ProcessPayment(amount);
}
}
5. 最小 API 配置
依赖注入:向依赖注入容器注册 PaymentContext 和具体策略类。
Endpoint:定义一个POST端点/pay,接受金额和方式作为参数,根据方式设置合适的支付策略,并处理支付。
using Payment.Api.Implementations;
using Payment.Api.Interfaces;
var builder = WebApplication.CreateBuilder(args);
//向容器中添加服务。
//注册服务
builder.Services.AddSingleton<IPaymentContext, PaymentContext>();
builder.Services.AddSingleton<WeiXinPalPaymentStrategy>();
builder.Services.AddSingleton<AliPaymentStrategy>();
builder.Services.AddSingleton<CreditCardPaymentStrategy>();
//配置Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
//配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapPost("/pay", async (decimal amount,
string method,
IPaymentContext paymentContext,
IServiceProvider serviceProvider) =>
{
IPaymentStrategy strategy = method.ToLower() switch
{
"weixin" => serviceProvider.GetService<WeiXinPaymentStrategy>(),
"ali" => serviceProvider.GetService<AliPaymentStrategy>(),
"creditcard" => serviceProvider.GetService<CreditCardPaymentStrategy>(),
_ => throw new NotSupportedException("选择的付款方式无效。")
};
paymentContext.SetPaymentStrategy(strategy);
paymentContext.ExecutePayment(amount);
return Results.Ok($"支付 {amount:C} 使用 {method} 处理成功.");
});
6.运行应用程序
构建并运行:使用 dotnet run 运行应用程序。
测试端点:您可以通过向 /pay 发送带有 JSON 有效负载的 POST 请求来测试付款处理。
三. 结论
通过将策略模式与 .NET 8.0 中的最小 API 集成并使用依赖项注入,我们创建了一个灵活且可维护的支付处理系统。这种方法允许您在运行时轻松切换不同的支付方式,并与 .NET 中的现代开发实践保持一致。