标签:wot jmm header FN over gpg head view 设计
Chain of Responsibility(CoR) 模式也叫职责链模式,是行为模式之一,该模式构造一系列分别担当不同职责的类的对象来共同完成一个任务,这些类的对象之间像链条一样紧密相连,所以被称作职责链模式。
抽象父类CarHandler,父类里持有本身的引用,且实现set方法:
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:
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:
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:
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 }
测试代码:
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 }
结果:
标签:wot jmm header FN over gpg head view 设计
原文地址:https://www.cnblogs.com/huaxueyihao/p/9153331.html