本文主要是介绍职责链模式,非常容易被忽视的设计模式之一(设计模式与开发实践 P13),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 现实实例
- 反例
- 优化
- 异步职责链
职责链模式在 C# 中是常见的,他的定义是:使多个对象都有机会处理请求,从而避免发送者和请求者之间的耦合关系,将对象连成一条链并传递该请求,直到有一个对象处理它为止
现实实例
上公交车要把硬币递给后排的售票员(现在应该不常见了)运气好第一个人就是售票员,负责要一直传递直到找到售票员
请求发送者只知道链中的第一个节点,弱化了发送者和接受者之间的强联系,如果不使用职责链模式,我们只能知道谁是售票员,才能把硬币给他
反例
假设你正在开发一个在线购物网站,其中有一个订单处理系统。在该系统中,订单需要经过一系列的验证和处理步骤,包括库存检查、支付验证、优惠券验证和物流处理
如果是一个程序员新手他有可能实现这样的代码,每个步骤都硬编码在里面,难以扩展和优化:
public class OrderProcessor
{public void ProcessOrder(Order order){// 库存检查bool stockAvailable = CheckStock(order);if (!stockAvailable){Console.WriteLine("库存不足");return;}// 支付验证bool paymentValidated = ValidatePayment(order);if (!paymentValidated){Console.WriteLine("支付验证失败");return;}// 优惠券验证bool couponValidated = ValidateCoupon(order);if (!couponValidated){Console.WriteLine("优惠券验证失败");return;}// 物流处理ProcessShipping(order);}private bool CheckStock(Order order){// 检查库存逻辑// ...}private bool ValidatePayment(Order order){// 支付验证逻辑// ...}private bool ValidateCoupon(Order order){// 优惠券验证逻辑// ...}private void ProcessShipping(Order order){// 物流处理逻辑// ...}
}public class Order
{// 订单数据// ...
}
优化
这是使用职责链模式优化的代码,把请求解耦分给不同的 Handler 执行,并通过设置 Next Handler 找到下一个职责任务,这就拆分了不同的执行节点,变得可扩展了
public abstract class OrderHandler
{protected OrderHandler NextHandler;public void SetNextHandler(OrderHandler handler){NextHandler = handler;}public abstract void ProcessOrder(Order order);
}public class StockCheckHandler : OrderHandler
{public override void ProcessOrder(Order order){bool stockAvailable = CheckStock(order);if (!stockAvailable){Console.WriteLine("库存不足");return;}if (NextHandler != null){NextHandler.ProcessOrder(order);}}private bool CheckStock(Order order){// 检查库存逻辑// ...}
}public class PaymentValidationHandler : OrderHandler
{public override void ProcessOrder(Order order){bool paymentValidated = ValidatePayment(order);if (!paymentValidated){Console.WriteLine("支付验证失败");return;}if (NextHandler != null){NextHandler.ProcessOrder(order);}}private bool ValidatePayment(Order order){// 支付验证逻辑// ...}
}public class CouponValidationHandler : OrderHandler
{public override void ProcessOrder(Order order){bool couponValidated = ValidateCoupon(order);if (!couponValidated){Console.WriteLine("优惠券验证失败");return;}if (NextHandler != null){NextHandler.ProcessOrder(order);}}private bool ValidateCoupon(Order order){// 优惠券验证逻辑// ...}
}public class ShippingHandler : OrderHandler
{public override void ProcessOrder(Order order){// 物流处理逻辑// ...}
}// 在客户端代码中构建职责链
public class Client
{public void Main(){OrderHandler stockCheckHandler = new StockCheckHandler();OrderHandler paymentValidationHandler = new PaymentValidationHandler();OrderHandler couponValidationHandler = new CouponValidationHandler();OrderHandler shippingHandler = new ShippingHandler();stockCheckHandler.SetNextHandler(paymentValidationHandler);paymentValidationHandler.SetNextHandler(couponValidationHandler);couponValidationHandler.SetNextHandler(shippingHandler);OrderProcessor orderProcessor = new OrderProcessor(stockCheckHandler);Order order = new Order();orderProcessor.ProcessOrder(order);}
}public class OrderProcessor
{private OrderHandler _orderHandler;public OrderProcessor(OrderHandler orderHandler){_orderHandler = orderHandler;}public void ProcessOrder(Order order){_orderHandler.ProcessOrder(order);}
}public class Order
{// 订单数据// ...
}
异步职责链
每个具体的处理器类都可以异步执行相应的任务,并将结果传递给下一个处理器。通过使用异步职责链模式,将注册过程的不同步骤解耦并异步处理,提高性能和响应速度
public abstract class RegistrationHandler
{protected RegistrationHandler NextHandler;public void SetNextHandler(RegistrationHandler handler){NextHandler = handler;}public abstract Task<bool> ProcessAsync(RegistrationRequest request);
}public class UsernameValidationHandler : RegistrationHandler
{public override async Task<bool> ProcessAsync(RegistrationRequest request){// 验证用户名是否有效await Task.Delay(1000); // 模拟异步操作bool isValid = !string.IsNullOrEmpty(request.Username);Console.WriteLine("Username validation completed");// 将结果传递给下一个处理器if (NextHandler != null){return await NextHandler.ProcessAsync(request) && isValid;}return isValid;}
}public class EmailValidationHandler : RegistrationHandler
{public override async Task<bool> ProcessAsync(RegistrationRequest request){// 验证电子邮件是否有效await Task.Delay(1000); // 模拟异步操作bool isValid = !string.IsNullOrEmpty(request.Email);Console.WriteLine("Email validation completed");// 将结果传递给下一个处理器if (NextHandler != null){return await NextHandler.ProcessAsync(request) && isValid;}return isValid;}
}public class AccountCreationHandler : RegistrationHandler
{public override async Task<bool> ProcessAsync(RegistrationRequest request){// 创建用户账户await Task.Delay(1000); // 模拟异步操作bool isSuccess = true; // 假设账户创建成功Console.WriteLine("Account creation completed");// 将结果传递给下一个处理器if (NextHandler != null){return await NextHandler.ProcessAsync(request) && isSuccess;}return isSuccess;}
}
这篇关于职责链模式,非常容易被忽视的设计模式之一(设计模式与开发实践 P13)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!