• 责任链模式(Chain of Responsibility)


    责任链模式是对象的行为模式。使多个对象都有机会处理请求,从而避免请求的发送者和接受者直接的耦合关系。
    1. public abstract class Handler {
    2. protected Handler successor;
    3. public abstract void handlerRequest(String condition);
    4. protected Handler getSuccessor() {
    5. return successor;
    6. }
    7. public void setSuccessor(Handler successor) {
    8. this.successor = successor;
    9. }
    10. }
    11. public class ConcreteHandler1 extends Handler{
    12. @Override
    13. public void handlerRequest(String condition) {
    14. // TODO Auto-generated method stub
    15. // 如果是自己的责任,就自己处理,负责传给下家处理
    16. if(condition.equals("ConcreteHandler1")){
    17. System.out.println( "ConcreteHandler1 handled ");
    18. return ;
    19. }else{
    20. System.out.println( "ConcreteHandler1 passed ");
    21. getSuccessor().handlerRequest(condition);
    22. }
    23. }
    24. public class ConcreteHandler2 extends Handler{
    25. @Override
    26. public void handlerRequest(String condition) {
    27. // TODO Auto-generated method stub
    28. // 如果是自己的责任,就自己处理,负责传给下家处理
    29. if(condition.equals("ConcreteHandler2")){
    30. System.out.println( "ConcreteHandler2 handled ");
    31. return ;
    32. }else{
    33. System.out.println( "ConcreteHandler2 passed ");
    34. getSuccessor().handlerRequest(condition);
    35. }
    36. }
    37. }
    38. public class ConcreteHandlerN extends Handler{
    39. @Override
    40. public void handlerRequest(String condition) {
    41. // TODO Auto-generated method stub
    42. System.out.println( "ConcreteHandlerN handled");
    43. }
    44. }
    45. //测试
    46. Handler handler1 = new ConcreteHandler1();
    47. Handler handler2 = new ConcreteHandler2();
    48. Handler handlern = new ConcreteHandlerN();
    49. //链起来
    50. handler1.setSuccessor(handler2);
    51. handler2.setSuccessor(handlern);
    52. //假设这个请求是ConcreteHandler2的责任
    53. handler1.handlerRequest("ConcreteHandler2");
    54. public static void main(String[] args) {
    55. // TODO Auto-generated method stub
    56. Handler handler1 = new ConcreteHandler1();
    57. Handler handler2 = new ConcreteHandler2();
    58. Handler handlern = new ConcreteHandlerN();
    59. //链起来
    60. handler1.setSuccessor(handler2);
    61. handler2.setSuccessor(handlern);
    62. //假设这个请求是ConcreteHandler2的责任
    63. handler1.handlerRequest("ConcreteHandler2");
    64. }

  • 相关阅读:
    获取店铺的所有商品API 返回值说明
    JVM虚拟机 总结很到位
    快速复现 实现 facenet-retinaface-pytorch 人脸识别 windows上 使用cpu实现
    使用开源软件Inno Setup制作软件安装包
    Vite创建React项目,另外一种更加简单的方法
    矩阵分析与应用+张贤达
    C++零碎记录(十三)
    电机控制器HIL测试系统:实现高效、安全的硬件在环验证
    ros之乌龟做圆周运动and订阅乌龟的位姿信息
    手机如何免费设置PDF区域高亮?
  • 原文地址:https://blog.csdn.net/qq_28256783/article/details/129093850