C#与设计模式如何提升代码质量与可维护性 面对复杂业务场景时如何选择合适的设计模式

引言:设计模式在现代软件开发中的核心价值
在当今快速迭代的软件开发环境中,代码质量与可维护性已成为决定项目成败的关键因素。C#作为一门强类型、面向对象的编程语言,与设计模式的结合能够显著提升软件架构的健壮性。设计模式不仅仅是理论概念,更是经过无数项目验证的最佳实践,它们能够帮助开发者解决常见的设计问题,降低代码耦合度,提高内聚性。
当我们面对复杂的业务场景时,设计模式的选择往往成为一项挑战。错误的模式选择不仅无法解决问题,反而可能引入新的复杂性。本文将深入探讨C#中常用的设计模式如何提升代码质量,并提供在复杂业务场景下选择合适设计模式的实用指南。
一、设计模式如何提升代码质量与可维护性
1.1 降低耦合度:依赖倒置原则的实践
设计模式的核心优势之一是降低模块间的耦合度。在C#中,通过接口和抽象类的合理使用,可以实现高度解耦的系统架构。
示例:不使用设计模式的紧耦合代码
// 紧耦合的支付处理类
public class PaymentProcessor
{
public void ProcessPayment(string paymentType, decimal amount)
{
if (paymentType == “CreditCard”)
{
// 直接依赖具体的信用卡处理逻辑
Console.WriteLine($”处理信用卡支付: {amount}”);
}
else if (paymentType == “PayPal”)
{
// 直接依赖具体的PayPal处理逻辑
Console.WriteLine($”处理PayPal支付: {amount}”);
}
// 每次新增支付方式都需要修改这个类
}
}
使用策略模式重构后的解耦代码
// 定义支付策略接口
public interface IPaymentStrategy
{
void ProcessPayment(decimal amount);
}

// 具体的信用卡支付策略
public class CreditCardPayment : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($”使用信用卡支付: {amount}”);
}
}

// 具体的PayPal支付策略
public class PayPalPayment : IPaymentStrategy
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($”使用PayPal支付: {amount}”);
}
}

// 支付上下文,与具体策略解耦
public class PaymentContext
{
private IPaymentStrategy _paymentStrategy;

public void SetPaymentStrategy(IPaymentStrategy strategy)
{
_paymentStrategy = strategy;
}

public void ExecutePayment(decimal amount)
{
_paymentStrategy.ProcessPayment(amount);
}
}

// 使用示例
public class Program
{
public static void Main()
{
var context = new PaymentContext();

// 可以在运行时动态切换策略
context.SetPaymentStrategy(new CreditCardPayment());
context.ExecutePayment(100.00m);

context.SetPaymentStrategy(new PayPalPayment());
context.ExecutePayment(200.00m);
}
}
代码质量提升分析
:
开闭原则
:新增支付方式时,无需修改现有代码,只需实现
IPaymentStrategy
接口
单一职责
:每个支付策略类只负责自己的支付逻辑
可测试性
:可以单独测试每个策略,Mock接口进行单元测试
1.2 提高扩展性:开闭原则的实现
设计模式让系统能够拥抱变化,通过抽象和多态实现优雅的扩展。
示例:使用工厂模式管理对象创建
// 产品接口
public interface ILogger
{
void Log(string message);
}

// 具体产品
public class FileLogger : ILogger
{
public void Log(string message)
{
File.AppendAllText(“log.txt”, $”{DateTime.Now}: {message}\n”);
}
}

public class DatabaseLogger : ILogger
{
public void Log(string message)
{
// 模拟数据库日志记录
Console.WriteLine($”[DB] {DateTime.Now}: {message}”);
}
}

public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine($”[Console] {DateTime.Now}: {message}”);
}
}

// 工厂类
public static class LoggerFactory
{
public static ILogger CreateLogger(string type)
{
return type switch
{
“File” => new FileLogger(),
“Database” => new DatabaseLogger(),
“Console” => new ConsoleLogger(),
_ => throw new ArgumentException(“未知的日志类型”)
};
}
}

// 使用示例
public class BusinessService
{
private readonly ILogger _logger;

public BusinessService(string loggerType)
{
_logger = LoggerFactory.CreateLogger(loggerType);
}

public void DoWork()
{
_logger.Log(“业务操作开始执行”);
// 业务逻辑…
_logger.Log(“业务操作执行完成”);
}
}
1.3 增强可读性与可维护性
良好的设计模式应用能让代码意图更加清晰,降低维护成本。
示例:使用建造者模式构建复杂对象
// 复杂的配置对象
public class ServerConfiguration
{
public string Host { get; private set; }
public int Port { get; private set; }
public bool EnableSsl { get; private set; }
public int Timeout { get; private set; }
public string ApiKey { get; private set; }

// 私有构造函数,强制使用建造者
private ServerConfiguration() { }

// 建造者类
public class Builder
{
private ServerConfiguration _config = new ServerConfiguration();

public Builder WithHost(string host)
{
_config.Host = host;
return this;
}

public Builder WithPort(int port)
{
_config.Port = port;
return this;
}

public Builder EnableSsl(bool enable = true)
{
_config.EnableSsl = enable;
return this;
}

public Builder WithTimeout(int timeout)
{
_config.Timeout = timeout;
return this;
}

public Builder WithApiKey(string apiKey)
{
_config.ApiKey = apiKey;
return this;
}

public ServerConfiguration Build()
{
// 验证配置
if (string.IsNullOrEmpty(_config.Host))
throw new InvalidOperationException(“Host is required”);
if (_config.Port == 0)
_config.Port = 443; // 默认端口

return _config;
}
}
}

// 使用示例
public class Program
{
public static void Main()
{
// 清晰的链式调用,代码可读性极高
var config = new ServerConfiguration.Builder()
.WithHost(“api.example.com”)
.WithPort(8080)
.EnableSsl()
.WithTimeout(30)
.WithApiKey(“secret-key”)
.Build();

Console.WriteLine($”配置: {config.Host}:{config.Port}, SSL: {config.EnableSsl}”);
}
}
二、复杂业务场景下的设计模式选择策略
2.1 识别业务场景的核心特征
在选择设计模式前,必须深入分析业务场景的特征:
业务场景分析矩阵
场景特征
适用模式
C#实现要点
对象创建复杂
工厂方法、抽象工厂、建造者
使用泛型和依赖注入
行为变化频繁
策略模式、状态模式
接口隔离,运行时切换
需要事件通知
观察者模式、中介者模式
事件总线、弱引用事件
对象访问控制
代理模式、装饰器模式
动态代理、AOP
算法结构固定
模板方法模式
抽象基类,钩子方法
2.2 复杂业务场景实战:电商订单处理系统
让我们通过一个复杂的电商订单处理场景,展示如何选择合适的设计模式。
场景描述
:
支持多种订单类型(普通订单、预售订单、团购订单)
支持多种支付方式
支持多种配送方式
订单状态流转复杂
需要支持促销规则计算
2.2.1 使用策略模式处理支付和配送
// 支付策略接口
public interface IPaymentStrategy
{
Task PayAsync(decimal amount);
bool SupportsRefund { get; }
}

// 配送策略接口
public interface IShippingStrategy
{
Task ShipAsync(Order order);
decimal CalculateCost(Order order);
}

// 具体支付实现
public class WeChatPayment : IPaymentStrategy
{
public bool SupportsRefund => true;

public async Task PayAsync(decimal amount)
{
// 调用微信支付SDK
await Task.Delay(100); // 模拟异步调用
return new PaymentResult { Success = true, TransactionId = “WX” + Guid.NewGuid() };
}
}

public class CreditCardPayment : IPaymentStrategy
{
public bool SupportsRefund => true;

public async Task PayAsync(decimal amount)
{
// 调用信用卡支付网关
await Task.Delay(150);
return new PaymentResult { Success = true, TransactionId = “CC” + Guid.NewGuid() };
}
}

// 具体配送实现
public class ExpressShipping : IShippingStrategy
{
public async Task ShipAsync(Order order)
{
await Task.Delay(200);
return new ShippingInfo
{
Company = “顺丰速运”,
TrackingNumber = “SF” + DateTime.Now.Ticks,
EstimatedDays = 2
};
}

public decimal CalculateCost(Order order)
{
return order.TotalWeight * 2.5m + 10m; // 基础费用+重量费用
}
}

public class StandardShipping : IShippingStrategy
{
public async Task ShipAsync(Order order)
{
await Task.Delay(300);
return new ShippingInfo
{
Company = “中通快递”,
TrackingNumber = “ZT” + DateTime.Now.Ticks,
EstimatedDays = 5
};
}

public decimal CalculateCost(Order order)
{
return order.TotalWeight * 1.2m + 5m;
}
}
2.2.2 使用状态模式管理订单状态流转
// 订单状态接口
public interface IOrderState
{
Task CancelAsync(Order order);
Task PayAsync(Order order, IPaymentStrategy payment);
Task ShipAsync(Order order, IShippingStrategy shipping);
Task CompleteAsync(Order order);
}

// 具体状态实现
public class PendingState : IOrderState
{
public async Task CancelAsync(Order order)
{
order.State = new CancelledState();
order.Status = “已取消”;
await SendNotificationAsync(order, “订单已取消”);
}

public async Task PayAsync(Order order, IPaymentStrategy payment)
{
var result = await payment.PayAsync(order.TotalAmount);
if (result.Success)
{
order.PaymentTransactionId = result.TransactionId;
order.State = new PaidState();
order.Status = “已支付”;
await SendNotificationAsync(order, “支付成功”);
}
else
{
throw new InvalidOperationException(“支付失败”);
}
}

public Task ShipAsync(Order order, IShippingStrategy shipping)
{
throw new InvalidOperationException(“订单未支付,无法发货”);
}

public Task CompleteAsync(Order order)
{
throw new InvalidOperationException(“订单未支付,无法完成”);
}
}

public class PaidState : IOrderState
{
public Task CancelAsync(Order order)
{
throw new InvalidOperationException(“已支付订单需要先退款才能取消”);
}

public Task PayAsync(Order order, IPaymentStrategy payment)
{
throw new InvalidOperationException(“订单已支付”);
}

public async Task ShipAsync(Order order, IShippingStrategy shipping)
{
var shippingInfo = await shipping.ShipAsync(order);
order.ShippingInfo = shippingInfo;
order.State = new ShippedState();
order.Status = “已发货”;
await SendNotificationAsync(order, $”订单已发货,快递公司: {shippingInfo.Company}”);
}

public Task CompleteAsync(Order order)
{
throw new InvalidOperationException(“订单未发货,无法完成”);
}
}

public class ShippedState : IOrderState
{
public Task CancelAsync(Order order)
{
throw new InvalidOperationException(“已发货订单无法取消”);
}

public Task PayAsync(Order order, IPaymentStrategy payment)
{
throw new InvalidOperationException(“订单已支付”);
}

public Task ShipAsync(Order order, IShippingStrategy shipping)
{
throw new InvalidOperationException(“订单已发货”);
}

public async Task CompleteAsync(Order order)
{
order.State = new CompletedState();
order.Status = “已完成”;
await SendNotificationAsync(order, “订单已完成”);
}
}

public class CompletedState : IOrderState
{
public Task CancelAsync(Order order) => throw new InvalidOperationException(“已完成订单无法取消”);
public Task PayAsync(Order order, IPaymentStrategy payment) => throw new InvalidOperationException(“订单已支付”);
public Task ShipAsync(Order order, IShippingStrategy shipping) => throw new InvalidOperationException(“订单已发货”);
public Task CompleteAsync(Order order) => throw new InvalidOperationException(“订单已完成”);
}

public class CancelledState : IOrderState
{
public Task CancelAsync(Order order) => throw new InvalidOperationException(“订单已取消”);
public Task PayAsync(Order order, IPaymentStrategy payment) => throw new InvalidOperationException(“订单已取消”);
public Task ShipAsync(Order order, IShippingStrategy shipping) => throw new InvalidOperationException(“订单已取消”);
public Task CompleteAsync(Order order) => throw new InvalidOperationException(“订单已取消”);
}
2.2.3 使用组合模式处理促销规则
// 促销规则接口
public interface IPromotionRule
{
string Name { get; }
decimal CalculateDiscount(Order order);
bool IsApplicable(Order order);
}

// 组合规则
public class CompositePromotion : IPromotionRule
{
private readonly List _rules = new List();

public string Name => “组合促销”;

public CompositePromotion AddRule(IPromotionRule rule)
{
_rules.Add(rule);
return this;
}

public decimal CalculateDiscount(Order order)
{
return _rules
.Where(r => r.IsApplicable(order))
.Sum(r => r.CalculateDiscount(order));
}

public bool IsApplicable(Order order)
{
return _rules.Any(r => r.IsApplicable(order));
}
}

// 具体规则
public class满减Rule : IPromotionRule
{
private readonly decimal _threshold;
private readonly decimal _discount;

public满减Rule(decimal threshold, decimal discount)
{
_threshold = threshold;
_discount = discount;
}

public string Name => $”满{_threshold}减{_discount}”;

public decimal CalculateDiscount(Order order)
{
return order.Subtotal >= _threshold ? _discount : 0;
}

public bool IsApplicable(Order order)
{
return order.Subtotal >= _threshold;
}
}

public class 会员折扣Rule : IPromotionRule
{
private readonly decimal _discountRate;

public 会员折扣Rule(decimal discountRate)
{
_discountRate = discountRate;
}

public string Name => $”会员折扣{_discountRate:P}”;

public decimal CalculateDiscount(Order order)
{
return order.Subtotal * _discountRate;
}

public bool IsApplicable(Order order)
{
return order.IsMember;
}
}
2.2.4 使用中介者模式协调复杂交互
// 订单处理中介者
public class OrderProcessingMediator
{
private readonly IPaymentStrategy _paymentStrategy;
private readonly IShippingStrategy _shippingStrategy;
private readonly IPromotionRule _promotionRule;
private readonly ILogger _logger;

public OrderProcessingMediator(
IPaymentStrategy paymentStrategy,
IShippingStrategy shippingStrategy,
IPromotionRule promotionRule,
ILogger logger)
{
_paymentStrategy = paymentStrategy;
_shippingStrategy = shippingStrategy;
_promotionRule = promotionRule;
_logger = logger;
}

public async Task ProcessOrderAsync(Order order)
{
try
{
_logger.Log($”开始处理订单: {order.Id}”);

// 1. 计算促销
var discount = _promotionRule.CalculateDiscount(order);
order.FinalAmount = order.Subtotal – discount;
_logger.Log($”促销折扣: {discount}, 最终金额: {order.FinalAmount}”);

// 2. 执行支付
var paymentResult = await _paymentStrategy.PayAsync(order.FinalAmount);
if (!paymentResult.Success)
{
return new OrderResult { Success = false, Message = “支付失败” };
}
order.PaymentTransactionId = paymentResult.TransactionId;
_logger.Log($”支付成功: {paymentResult.TransactionId}”);

// 3. 安排配送
var shippingInfo = await _shippingStrategy.ShipAsync(order);
order.ShippingInfo = shippingInfo;
_logger.Log($”配送已安排: {shippingInfo.Company} – {shippingInfo.TrackingNumber}”);

// 4. 更新状态
order.State = new CompletedState();
order.Status = “订单处理完成”;

_logger.Log($”订单处理完成: {order.Id}”);

return new OrderResult
{
Success = true,
OrderId = order.Id,
TrackingNumber = shippingInfo.TrackingNumber
};
}
catch (Exception ex)
{
_logger.Log($”订单处理失败: {ex.Message}”);
return new OrderResult { Success = false, Message = ex.Message };
}
}
}
2.3 选择设计模式的决策流程
面对复杂业务场景时,建议遵循以下决策流程:
// 设计模式选择器示例
public class DesignPatternSelector
{
public static IPatternRecommendation AnalyzeScenario(ScenarioAnalysis analysis)
{
var recommendations = new List();

// 1. 分析对象创建复杂度
if (analysis.CreationComplexity > 7)
{
recommendations.Add(new PatternRecommendation
{
Pattern = “Factory/Builder”,
Reason = “对象创建逻辑复杂,需要分离创建与使用”,
Priority = Priority.High
});
}

// 2. 分析行为变化频率
if (analysis.BehaviorVariations > 5)
{
recommendations.Add(new PatternRecommendation
{
Pattern = “Strategy”,
Reason = “多种算法/行为需要运行时切换”,
Priority = Priority.High
});
}

// 3. 分析状态流转复杂度
if (analysis.StateTransitions > 10)
{
recommendations.Add(new PatternRecommendation
{
Pattern = “State”,
Reason = “状态流转逻辑复杂,需要状态模式管理”,
Priority = Priority.Medium
});
}

// 4. 分析对象间通信复杂度
if (analysis.ObjectCommunications > 8)
{
recommendations.Add(new PatternRecommendation
{
Pattern = “Mediator/Observer”,
Reason = “对象间通信复杂,需要中介者或观察者模式”,
Priority = Priority.Medium
});
}

// 5. 分析是否需要扩展包装
if (analysis.NeedsExtensionWrapping)
{
recommendations.Add(new PatternRecommendation
{
Pattern = “Decorator/Proxy”,
Reason = “需要在不改变原有对象的基础上增加功能”,
Priority = Priority.Low
});
}

return new CompositeRecommendation(recommendations);
}
}

// 分析模型
public class ScenarioAnalysis
{
public int CreationComplexity { get; set; } // 对象创建复杂度 1-10
public int BehaviorVariations { get; set; } // 行为变体数量
public int StateTransitions { get; set; } // 状态转换数量
public int ObjectCommunications { get; set; } // 对象间通信复杂度
public bool NeedsExtensionWrapping { get; set; } // 是否需要扩展包装
}
三、C#中设计模式的最佳实践
3.1 依赖注入与设计模式的结合
在现代C#开发中,依赖注入(DI)容器与设计模式的结合是最佳实践:
// 在ASP.NET Core中配置策略模式
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// 注册支付策略工厂
services.AddSingleton();

// 注册具体的支付策略
services.AddTransient();
services.AddTransient();
services.AddTransient();

// 注册配送策略
services.AddTransient();
services.AddTransient();

// 注册订单处理服务
services.AddTransient();
}
}

// 策略工厂
public interface IPaymentStrategyFactory
{
IPaymentStrategy Create(string paymentType);
}

public class PaymentStrategyFactory : IPaymentStrategyFactory
{
private readonly IServiceProvider _serviceProvider;

public PaymentStrategyFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public IPaymentStrategy Create(string paymentType)
{
return paymentType switch
{
“CreditCard” => _serviceProvider.GetRequiredService(),
“PayPal” => _serviceProvider.GetRequiredService(),
“WeChat” => _serviceProvider.GetRequiredService(),
_ => throw new ArgumentException($”不支持的支付类型: {paymentType}”)
};
}
}
3.2 使用现代C#特性增强设计模式
示例:使用记录类型(Record)和模式匹配
// 使用record定义不可变的数据传输对象
public record PaymentResult(bool Success, string TransactionId, string ErrorMessage = null);

// 使用记录类型定义订单状态
public record OrderState(string Status, DateTime Timestamp);

// 使用模式匹配简化状态处理
public class ModernOrderProcessor
{
public async Task ProcessOrderAsync(Order order, IPaymentStrategy payment)
{
var result = await payment.PayAsync(order.TotalAmount);

// 模式匹配简化条件判断
var newState = result switch
{
{ Success: true } => new OrderState(“Paid”, DateTime.UtcNow),
{ Success: false, ErrorMessage: var error } =>
throw new InvalidOperationException($”支付失败: {error}”),
_ => throw new InvalidOperationException(“未知的支付结果”)
};

order.State = newState;
}
}
3.3 异步编程与设计模式
// 异步策略模式
public interface IAsyncPaymentStrategy
{
Task PayAsync(decimal amount, CancellationToken cancellationToken = default);
}

// 使用CancellationToken支持取消操作
public class AsyncCreditCardPayment : IAsyncPaymentStrategy
{
public async Task PayAsync(decimal amount, CancellationToken cancellationToken = default)
{
try
{
// 模拟异步网络调用
await Task.Delay(2000, cancellationToken);
return new PaymentResult(true, “CC-” + Guid.NewGuid());
}
catch (OperationCanceledException)
{
return new PaymentResult(false, null, “支付已取消”);
}
}
}

// 异步中介者模式
public class AsyncOrderMediator
{
private readonly IEnumerable _paymentStrategies;
private readonly IAsyncShippingStrategy _shippingStrategy;

public async Task ProcessOrderAsync(
Order order,
string paymentType,
CancellationToken cancellationToken = default)
{
// 并行执行支付和配送计算
var paymentTask = _paymentStrategies
.First(s => s.GetType().Name.Contains(paymentType))
.PayAsync(order.TotalAmount, cancellationToken);

var shippingCostTask = _shippingStrategy.CalculateCostAsync(order, cancellationToken);

await Task.WhenAll(paymentTask, shippingCostTask);

var paymentResult = await paymentTask;
var shippingCost = await shippingCostTask;

if (!paymentResult.Success)
return new OrderResult { Success = false };

return new OrderResult
{
Success = true,
TotalCost = order.TotalAmount + shippingCost
};
}
}
四、设计模式选择的常见陷阱与规避策略
4.1 过度设计:模式不是银弹
陷阱示例
:
// 过度设计:为简单的CRUD操作使用复杂模式
public class SimpleCrudService
{
// 不必要的抽象
public interface ICommand { Task ExecuteAsync(T entity); }
public interface IQuery { Task GetAsync(int id); }

// 简单操作被拆分成过多模式
public class CreateCommand : ICommand { /* … */ }
public class ReadQuery : IQuery { /* … */ }
public class UpdateCommand : ICommand { /* … */ }
public class DeleteCommand : ICommand { /* … */ }
}
正确做法
:
// 简单直接的实现,直到真正需要扩展
public class UserService
{
public async Task GetUserAsync(int id) { /* … */ }
public async Task CreateUserAsync(User user) { /* … */ }
public async Task UpdateUserAsync(User user) { /* … */ }
public async Task DeleteUserAsync(int id) { /* … */ }
}
4.2 模式误用:选择错误的模式
常见误用场景
:
单例模式
:在Web应用中导致线程安全问题
工厂模式
:用于创建简单对象,增加不必要的复杂性
观察者模式
:在不需要事件驱动的场景中使用
规避策略
:
// 使用依赖注入代替单例模式
public class OrderService
{
private readonly IOrderRepository _repository;
private readonly ILogger _logger;

// 通过构造函数注入,避免单例的全局状态
public OrderService(IOrderRepository repository, ILogger logger)
{
_repository = repository;
_logger = logger;
}
}

// 在Startup.cs中配置
public void ConfigureServices(IServiceCollection services)
{
// 使用Scoped生命周期,避免单例问题
services.AddScoped();
services.AddScoped();
services.AddScoped();
}
4.3 模式混合:当多个模式冲突时
解决方案
:
// 使用组合模式而非继承
public interface IOrderProcessor
{
Task ProcessAsync(Order order);
}

// 基础处理器
public class BaseOrderProcessor : IOrderProcessor
{
public virtual async Task ProcessAsync(Order order)
{
// 基础处理逻辑
}
}

// 装饰器模式包装处理器
public class LoggingOrderProcessor : IOrderProcessor
{
private readonly IOrderProcessor _inner;
private readonly ILogger _logger;

public LoggingOrderProcessor(IOrderProcessor inner, ILogger logger)
{
_inner = inner;
_logger = logger;
}

public async Task ProcessAsync(Order order)
{
_logger.Log($”开始处理订单: {order.Id}”);
await _inner.ProcessAsync(order);
_logger.Log($”完成处理订单: {order.Id}”);
}
}

public class ValidationOrderProcessor : IOrderProcessor
{
private readonly IOrderProcessor _inner;

public ValidationOrderProcessor(IOrderProcessor inner)
{
_inner = inner;
}

public async Task ProcessAsync(Order order)
{
if (order.Subtotal <= 0) throw new InvalidOperationException("订单金额无效"); await _inner.ProcessAsync(order); } } // 组合使用 public class Program { public static IOrderProcessor CreateProcessor() { var processor = new BaseOrderProcessor(); processor = new ValidationOrderProcessor(processor); processor = new LoggingOrderProcessor(processor, new ConsoleLogger()); return processor; } } 五、总结与最佳实践建议 5.1 设计模式选择决策树 // 伪代码:设计模式选择决策逻辑 public class DesignPatternDecisionTree { public string RecommendPattern(ScenarioContext context) { // 1. 是否涉及对象创建? if (context.HasComplexCreation) { return context.CreationVariations switch { > 3 => “AbstractFactory”,
> 1 => “FactoryMethod”,
_ => “SimpleFactory”
};
}

// 2. 是否涉及行为变化?
if (context.HasBehaviorVariations)
{
return context.BehaviorRuntimeSwitching
? “Strategy”
: “TemplateMethod”;
}

// 3. 是否涉及状态管理?
if (context.HasStateTransitions)
{
return context.StateComplexity switch
{
> 5 => “State”,
_ => “SimpleState”
};
}

// 4. 是否涉及对象通信?
if (context.HasComplexCommunication)
{
return context.IsEventDriven
? “Observer”
: “Mediator”;
}

// 5. 是否需要功能扩展?
if (context.NeedsExtension)
{
return context.NeedsTransparentExtension
? “Decorator”
: “Proxy”;
}

return “No pattern needed – keep it simple”;
}
}
5.2 实用建议清单
从简单开始
:先实现简单直接的代码,当发现重复模式或扩展困难时再考虑设计模式
理解业务本质
:设计模式是业务逻辑的抽象,不是炫技工具
团队共识
:确保团队成员理解并接受所使用的模式
文档化
:为复杂的模式实现编写清晰的文档和注释
测试驱动
:设计模式应让测试更容易,而不是更难
性能考量
:某些模式(如装饰器链)可能影响性能,需要权衡
现代特性
:结合C#最新特性(如记录类型、模式匹配)使用设计模式
5.3 持续演进的设计
// 设计演进示例:从简单到复杂
// 阶段1:简单实现
public class OrderServiceV1
{
public void ProcessOrder(Order order) { /* … */ }
}

// 阶段2:发现需要支持多种支付
public class OrderServiceV2
{
private readonly IPaymentStrategy _paymentStrategy;
// 使用策略模式
}

// 阶段3:发现需要支持多种配送
public class OrderServiceV3
{
private readonly IPaymentStrategy _paymentStrategy;
private readonly IShippingStrategy _shippingStrategy;
// 组合多个策略模式
}

// 阶段4:发现状态流转复杂
public class OrderServiceV4
{
private readonly IOrderState _currentState;
// 引入状态模式
}

// 阶段5:需要支持促销规则
public class OrderServiceV5
{
private readonly IPromotionRule _promotionRule;
// 引入组合模式处理规则
}
通过遵循这些原则和实践,开发者可以在C#项目中有效地应用设计模式,显著提升代码质量和可维护性,同时避免过度设计和模式误用的陷阱。记住,设计模式是工具,不是目的,最终目标是创建清晰、可维护、可扩展的软件系统。