0%

Aop链式调用


多个aop如果叠加
采用了责任链的模式
这里写图片描述
使用ConcerteHandler实现类实现HandleProcess接口同时这个实现类又组合了这个接口,通过successor判断来进行链式调用


首先我们新建一个Handler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public abstract class Handler {

private Handler successor;

public Handler getSuccessor() {
return successor;
}

public void setSuccessor(Handler successor) {
this.successor = successor;
}

public void execute(){
handleProcess();
if(successor != null){
successor.execute();
}
}

protected abstract void handleProcess();
}


下面我们看看client端实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class ChainClient {
static class HandlerA extends Handler{

@Override
protected void handleProcess() {
System.out.println("handler by a");
}
}

static class HandlerB extends Handler{

@Override
protected void handleProcess() {
System.out.println("handler by b");
}
}

static class HandlerC extends Handler{

@Override
protected void handleProcess() {
System.out.println("handler by c");
}
}

public static void main(String[] args) {
Handler handlerA = new HandlerA();
Handler handlerB = new HandlerB();
Handler handlerC = new HandlerC();
handlerA.setSuccessor(handlerB);
handlerB.setSuccessor(handlerC);
handlerA.execute();
}
}

由此我们实现了链式调用,但是我们也发现了每次都需要设置从属关系。


下面我们对上面方法改造,使用另外一个Chain对再下面的代码进行一次封装

1
2
3
4
5
6
7
8
public static void main(String[] args) {
Handler handlerA = new HandlerA();
Handler handlerB = new HandlerB();
Handler handlerC = new HandlerC();
handlerA.setSuccessor(handlerB);
handlerB.setSuccessor(handlerC);
handlerA.execute();
}


下面我们新建一个ChainHandler

1
2
3
4
5
6
7
8
public abstract class ChainHandler {

public void execute(Chain chain){
handleProcess();
chain.proceed();
}
protected abstract void handleProcess();
}


Chain对链式关系封装起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Chain {
private List<ChainHandler> handlers;

private int index = 0;

public Chain(List<ChainHandler> handlers) {
this.handlers = handlers;
}
public void proceed(){
if(index >= handlers.size()){
return;
}
handlers.get(index++).execute(this);
}
}


下面我们看一下如何实现调用类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ChainClient {
static class ChainHandlerA extends ChainHandler{
@Override
protected void handleProcess() {
System.out.println("handler by chain a");
}
}
static class ChainHandlerB extends ChainHandler{
@Override
protected void handleProcess() {
System.out.println("handler by chain b");
}
}
static class ChainHandlerC extends ChainHandler{
@Override
protected void handleProcess() {
System.out.println("handler by chain c");
}
}
public static void main(String[] args) {
List<ChainHandler> handlers = Arrays.asList(
new ChainHandlerA(),
new ChainHandlerB(),
new ChainHandlerC()
);
Chain chain = new Chain(handlers);
chain.proceed();
}
}