什么意思呢?
就是有这么一个链条,你也不用管它具体怎么链的,你只需要给它一个输入,它就能找到恰当的一环来处理你的输入,就这么个意思。很显然,这对于使用者来说是非常方便的。
类图
类图.png调用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
AbstractReceiver chain = installChain();
chain.chainElementInput(AbstractReceiver.receiver2);
chain.chainElementInput(AbstractReceiver.receiver1);
chain.chainElementInput(AbstractReceiver.receiver3);
}
/**
* 组装责任链
* @return
*/
public static AbstractReceiver installChain() {
AbstractReceiver receiver1 = new Receiver1(AbstractReceiver.receiver1);
AbstractReceiver receiver2 = new Receiver2(AbstractReceiver.receiver2);
AbstractReceiver receiver3 = new Receiver3(AbstractReceiver.receiver3);
receiver1.setNextRecevier(receiver2);
receiver2.setNextRecevier(receiver3);
return receiver1;
}
}
结果
com.company.Receiver2
com.company.Receiver1
com.company.Receiver3
Process finished with exit code 0
抽象接收者
package com.company;
public abstract class AbstractReceiver {
public static int receiver1 = 1;
public static int receiver2 = 2;
public static int receiver3 = 3;
protected int receiverIndex;
protected AbstractReceiver nextRecevier;
public void setNextRecevier(AbstractReceiver nextRecevier) {
this.nextRecevier = nextRecevier;
}
/**
* 控制恰当链中的某一环来处理。
* @param inputIndex
*/
protected void chainElementInput(int inputIndex) {
if (inputIndex <= this.receiverIndex) {
printInformation(this.receiverIndex);
return;
} else {
this.nextRecevier.chainElementInput(inputIndex);
}
}
abstract public void printInformation(int receiverIndex);
}
接收者1
package com.company;
public class Receiver1 extends AbstractReceiver {
public Receiver1(int index) {
this.receiverIndex = index;
}
@Override
public void printInformation(int receiverIndex) {
System.out.println(this.getClass().getName());
}
}
接收者2
package com.company;
public class Receiver2 extends AbstractReceiver {
public Receiver2(int index) {
this.receiverIndex = index;
}
@Override
public void printInformation(int receiverIndex) {
System.out.println(this.getClass().getName());
}
}
接收者3
package com.company;
public class Receiver3 extends AbstractReceiver {
public Receiver3(int index) {
this.receiverIndex = index;
}
@Override
public void printInformation(int receiverIndex) {
System.out.println(this.getClass().getName());
}
}
多谢捧场
如果您觉得我的文章有价值,那么赏脸打赏一个,鄙人感激不尽。不过,不打赏看看也是好的,如果有不对的地方,还请您多多指正。
网友评论