【JAVA】-调用链设计demo

【JAVA】-调用链设计demo

  • 1-JAVA链式调用
    • 1-1 执行链
    • 1-2 执行者
    • 1-3 程序调用者,执行链的主要实现
    • 1-4 程序调用者,执行链的主要实现

1-JAVA链式调用

1-1 执行链

主要作用是执行

public interface ExectorChain {
    void execute();
}

1-2 执行者

执行链上的元素,主要是执行动作的具体实现

public interface Executor{
        void execute(ExectorChain chain);
}

1-3 程序调用者,执行链的主要实现

public  class DefaultExectorChain implements ExectorChain {

    private final List<Executor> ExecutorList = new LinkedList();

    private int position;

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public void addExecutor(Executor executor) {
        ExecutorList.add(executor);
    }

    @Override
    public void execute() {
        while (position < this.ExecutorList.size()) {
            Executor executor = ExecutorList.get(position);
            position = position + 1;
            executor.execute(this);
        }
    }

    public static void main(String[] args) {
        DefaultExectorChain chain = new DefaultExectorChain();
        chain.addExecutor(new Executor1());
        chain.addExecutor(new Executor2());
        chain.addExecutor(new Executor3());
        chain.execute();
    }
}

1-4 程序调用者,执行链的主要实现

public class Executor1 implements Executor {
    @Override
    public void execute(ExectorChain chain) {
        System.out.println("--------------------Hello World");
    }
}
public class Executor2 implements Executor {
    @Override
    public void execute(ExectorChain chain) {
        System.out.println("--------------------1111111");
    }
}
public class Executor3 implements Executor {
    @Override
    public void execute(ExectorChain chain) {
        System.out.println("--------------------2222222");
    }
}

你可能感兴趣的:(【JAVA】)