设计模式之职责链模式
Chain of Responsibility(CoR) 模式也叫职责链模式,是行为模式之一,该模式构造一系列分别担当不同职责的类的对象来共同完成一个任务,这些类的对象之间像链条一样紧密相连,所以被称作职责链模式。
抽象父类CarHandler,父类里持有本身的引用,且实现set方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.cor1; 2 3 public abstract class CarHandler { 4 5 protected CarHandler nextCarHandler; 6 7 public abstract void HandlerCar(); 8 9 public void setNextCarHandler(CarHandler carHandler){ 10 this.nextCarHandler = carHandler; 11 } 12 }
具体的实现类CarHeaderHandler:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.cor1; 2 3 public class CarHeaderHandler extends CarHandler { 4 5 @Override 6 public void HandlerCar() { 7 System.out.println("组装车头"); 8 if(this.nextCarHandler != null){ 9 this.nextCarHandler.HandlerCar(); 10 } 11 } 12 13 14 15 }
具体的实现类CarBodyHandler:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.cor1; 2 3 public class CarBodyHandler extends CarHandler { 4 5 @Override 6 public void HandlerCar() { 7 System.out.println("组装车身"); 8 if(this.nextCarHandler != null){ 9 this.nextCarHandler.HandlerCar(); 10 } 11 } 12 13 }
具体的实现类CarTailHandler:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.cor1; 2 3 public class CarTailHandler extends CarHandler { 4 5 @Override 6 public void HandlerCar() { 7 System.out.println("组装车尾"); 8 if(this.nextCarHandler != null){ 9 this.nextCarHandler.HandlerCar(); 10 } 11 } 12 13 }
测试代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.cor1; 2 3 public class MainClass { 4 5 public static void main(String[] args) { 6 CarHandler headH = new CarHeaderHandler(); 7 CarHandler carBodyHandler = new CarBodyHandler(); 8 CarTailHandler carTailHandler = new CarTailHandler(); 9 10 headH.setNextCarHandler(carBodyHandler); 11 carBodyHandler.setNextCarHandler(carTailHandler); 12 13 headH.HandlerCar(); 14 15 } 16 17 }
结果: