基于链表实现责任链设计模式

基于数据库实现责任链设计模式

环境搭建

ChainHandler

public interface ChainHandler {
    void service();
}

BaseGateWay

@Service
public class BaseGateWay implements ChainHandler {
    @Autowired
    private BlackHandler blackHandler;
    @Autowired
    private SqlHandler sqlHandler;

    private List chain = new LinkedList();

    @PostConstruct
    public void init() {
        chain.add(blackHandler);
        chain.add(sqlHandler);
    }

    /**
     * service调用此方法即可实现责任链的处理
     */
    @Override
    public void service() {
        for (ChainHandler chainHandler : chain) {
            chainHandler.service();
        }
    }
}

SqlHandler

@Component
public class SqlHandler implements ChainHandler {
    @Override
    public void service() {
        System.out.println(">>>>>>>>>处理SQL注入");
    }
}

BlackHandler

@Component
public class BlackHandler implements ChainHandler {
    @Override
    public void service() {
        System.out.println(">>>>>>>>>处理黑名单");
    }
}

GateWayController

@RestController
public class GateWayController {
    @Autowired
    private BaseGateWay base;
    @RequestMapping(value = "/gateway")
    public String gateway(){
        base.service();
        return "success";
    }
}

GateWayApp

   @SpringBootApplication
    public class GateWayApp {
        public static void main(String[] args) {
            SpringApplication.run(GateWayApp.class, args);
        }
    }

yml

server:
  servlet:
    context-path: /
  port: 8088
spring:
  application:
    name: utils
  datasource:
    url: jdbc:mysql://localhost:3306/designers?characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

测试

http://localhost:8088/gateway

你可能感兴趣的:(设计模式系列,链表,设计模式)