说明
- 使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
角色
- 抽象请求处理者
- 具体请求处理者:包含下一个具体请求处理者的引用
- 客户端:请求发送者
代码实现
public interface IHandSV {
void setNext(IHandSV hand);
void excute(String request);
String getType();
void doSomething();
}
public abstract class HandSVImpl implements IHandSV{
protected IHandSV nextHand;
@Override
public void excute(String request){
if(request.equals(getType())){
this.doSomething();
}else{
if(nextHand != null){
nextHand.excute(request);
}else{
System.out.println("无流程,结束");
}
}
}
@Override
public void setNext(IHandSV nextHand){
this.nextHand = nextHand;
}
}
public class Hand1SVImpl extends HandSVImpl implements IHandSV {
@Override
public String getType() {
return "1";
}
@Override
public void doSomething() {
System.out.println("我是1");
}
}
public class Hand2SVImpl extends HandSVImpl implements IHandSV {
@Override
public String getType() {
return "2";
}
@Override
public void doSomething() {
System.out.println("我是2");
}
}
public class Hand3SVImpl extends HandSVImpl implements IHandSV {
@Override
public String getType() {
return "3";
}
@Override
public void doSomething() {
System.out.println("我是3");
}
}
public interface ICommand {
void excute();
}
public class CommadDealImpl implements ICommand {
private IHandSV handSV1;
private IHandSV handSV2;
private IHandSV handSV3;
CommadDealImpl(){
handSV1 = new Hand1SVImpl();
handSV2 = new Hand2SVImpl();
handSV3 = new Hand3SVImpl();
handSV1.setNext(handSV2);
handSV2.setNext(handSV3);
}
@Override
public void excute() {
handSV1.excute("3");
}
}
public class Invoke {
private ICommand command;
Invoke(ICommand command){
this.command = command;
}
void action(){
this.command.excute();
}
}
public class Test {
public static void main(String[] args){
ICommand command = new CommadDealImpl();
Invoke invoke = new Invoke(command);
invoke.action();
}
}