简介:
责任链模式通俗点讲就是,打开层次箱子,最终发现真正的珠宝。
模式:
1.假设层层箱子分别为A、B、C、D,珠宝为X。
2.先将X放在D中,那么D认为X是珠宝;在把D放在C中,那么C认为D是珠宝;再把C放在B中,那么B认为C是珠宝;再把B放在A中,那么A认为B是珠宝。
3.执行A-B-C-D-X.
代码:
1.箱子抽象为接口
1 package com.bluejie.bluej.java.design.chain; 2 3 import com.bluejie.bluej.logUtil.LogUtil; 4 import org.slf4j.Logger; 5 6 /** 7 * Created by bluej on 2018/2/1. 8 */ 9 public interface Handler {10 11 Logger log = LogUtil.instance(Handler.class);12 13 void doHandle(Executor executor);14 }
2.各层箱子实现类
1 package com.bluejie.bluej.java.design.chain; 2 3 /** 4 * Created by bluej on 2018/2/1. 5 */ 6 public class LogHandler implements Handler { 7 @Override 8 public void doHandle(Executor executor) { 9 log.info("--LogHandler--");10 executor.doExecutor();11 }12 }
1 package com.bluejie.bluej.java.design.chain; 2 3 /** 4 * Created by bluej on 2018/2/1. 5 */ 6 public class ParamaterHandler implements Handler { 7 @Override 8 public void doHandle(Executor executor) { 9 log.info("--ParamaterHandler--");10 executor.doExecutor();11 }12 }
1 package com.bluejie.bluej.java.design.chain; 2 3 /** 4 * Created by bluej on 2018/2/1. 5 */ 6 public class ServiceHandler implements Handler { 7 @Override 8 public void doHandle(Executor executor) { 9 log.info("--ServiceHandler--");10 executor.doExecutor();11 }12 }
3.珠宝抽象为接口
1 package com.bluejie.bluej.java.design.chain; 2 3 import com.bluejie.bluej.logUtil.LogUtil; 4 import org.slf4j.Logger; 5 6 /** 7 * Created by bluej on 2018/2/1. 8 */ 9 public interface Executor {10 Logger log = LogUtil.instance(Executor.class);11 12 void doExecutor();13 }
4.珠宝实现类
1 package com.bluejie.bluej.java.design.chain; 2 3 /** 4 * Created by bluej on 2018/2/1. 5 */ 6 public class ExecutorService implements Executor { 7 @Override 8 public void doExecutor() { 9 log.info("--ExecutorService--");10 }11 }
5.执行demo
1 package com.bluejie.bluej.java.design.chain; 2 3 4 import java.util.ArrayList; 5 import java.util.Arrays; 6 import java.util.Collections; 7 import java.util.List; 8 9 /**10 * Created by bluej on 2018/2/1.11 */12 public class ChainDemo {13 private static ChainDemo chainDemo =new ChainDemo();14 15 public static void main(String[] args) {16 chainDemo.execute().doExecutor();17 }18 19 private Executor execute(){20 21 Executor executor = new ExecutorService();22 ListhandleList = new ArrayList<>();23 handleList.add(new LogHandler());24 handleList.add(new ParamaterHandler());25 handleList.add(new ServiceHandler());26 Collections.reverse(handleList);27 28 for (int i = 0 ;i
6.执行结果
0122018-02-02 00:33:29,270 [main] INFO com.bluejie.bluej.java.design.chain.Handler.doHandle - --LogHandler--2018-02-02 00:33:29,276 [main] INFO com.bluejie.bluej.java.design.chain.Handler.doHandle - --ParamaterHandler--2018-02-02 00:33:29,276 [main] INFO com.bluejie.bluej.java.design.chain.Handler.doHandle - --ServiceHandler--2018-02-02 00:33:29,276 [main] INFO com.bluejie.bluej.java.design.chain.Executor.doExecutor - --ExecutorService--