设计模式——责任链模式(二)

package org.example.design.chain.custom;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HandlerBaseChain<Q, R> {
    private static final Logger log = LoggerFactory.getLogger(HandlerBaseChain.class);
    private HandlerBaseCommand<Q, R>[] commands;

    public HandlerBaseChain() {
    }

    public void setCommands(HandlerBaseCommand<Q, R>[] commands) {
        if (commands == null) {
            throw new IllegalArgumentException();
        } else {
            this.commands = commands;
        }
    }

    /**
     *
     * @param context
     * @return true表示可以执行下一个command
     */
    public boolean execute(HandlerBaseContext<Q, R> context) {
        if (context == null) {
            throw new IllegalArgumentException();
        } else {
            boolean executeResult = false;
            Exception executeException = null;
            HandlerBaseCommand[] var4 = this.commands;
            int var5 = var4.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                HandlerBaseCommand<Q, R> command = var4[var6];
                String commandDesc = command.getCommandDesc();
                long startTime = System.currentTimeMillis();

                try {
                    executeResult = command.execute(context);
                    long endTime = System.currentTimeMillis();
                    if (!executeResult) {
                        log.debug("执行职责[{}]失败。耗时:{}ms", commandDesc, endTime - startTime);
                        break;
                    }

                    log.debug("执行职责[{}]成功。耗时:{}ms", commandDesc, endTime - startTime);
                } catch (Exception var13) {
                    executeException = var13;
                    log.error("执行职责[{}]异常。", commandDesc);
                    log.error("异常堆栈:", var13);
                    break;
                }
            }

            return executeException != null && !executeResult;
        }
    }
}


public interface HandlerBaseCommand<Q, P> {
    boolean execute(HandlerBaseContext<Q, P> var1);

    String getCommandDesc();
}


import java.beans.ConstructorProperties;

public class HandlerBaseContext<Q, P> {
    private Q request;
    private P response;

    public void clear() {
        this.request = null;
        this.response = null;
    }

    public HandlerBaseContext() {
    }

    @ConstructorProperties({"request", "response"})
    public HandlerBaseContext(Q request, P response) {
        this.request = request;
        this.response = response;
    }

    public Q getRequest() {
        return this.request;
    }

    public P getResponse() {
        return this.response;
    }

    public void setRequest(Q request) {
        this.request = request;
    }

    public void setResponse(P response) {
        this.response = response;
    }
}


@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HandlerChain {
    String[] commands();
}
package org.example.design.chain.custom;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class HandlerChainAnnotationBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    public HandlerChainAnnotationBeanPostProcessor() {
    }

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        HandlerChain handlerChain = (HandlerChain)bean.getClass().getAnnotation(HandlerChain.class);
        if (handlerChain != null && bean instanceof HandlerBaseChain) {
            String[] commands = handlerChain.commands();
            if (commands.length == 0) {
                return bean;
            }

            HandlerBaseCommand[] handlerBaseCommands = new HandlerBaseCommand[commands.length];

            for(int index = 0; index < commands.length; ++index) {
                HandlerBaseCommand command = (HandlerBaseCommand)this.applicationContext.getBean(commands[index]);
                handlerBaseCommands[index] = command;
            }

            ((HandlerBaseChain)bean).setCommands(handlerBaseCommands);
        }

        return bean;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
package org.example.design.chain;

import org.example.design.chain.custom.HandlerBaseCommand;
import org.example.design.chain.custom.HandlerBaseContext;
import org.springframework.stereotype.Component;

import java.util.Map;

// 获取客户信息
@Component
public class GetCustomerInfoCommand implements HandlerBaseCommand<Map, Map> {

    @Override
    public boolean execute(HandlerBaseContext<Map, Map> ctx) {
        System.out.println("GetCustomerInfo ");
        ctx.getResponse().put("getCustomerInfo", "ok");
        return true;
    }

    @Override
    public String getCommandDesc() {
        return "获取客户信息";
    }
}



// 试车(继承Command)
@Component
public class TestDriveVehicleCommand implements HandlerBaseCommand<Map, Map> {

    @Override
    public boolean execute(HandlerBaseContext<Map, Map> ctx) {
        System.out.println("Test drive the vehicle");
        ctx.getResponse().put("testDriveVehicle","ok");
        return true;
    }

    @Override
    public String getCommandDesc() {
        return "试车";
    }
}


// 销售谈判
@Component
public class NegotiateSaleCommand implements HandlerBaseCommand<Map, Map> {

    @Override
    public boolean execute(HandlerBaseContext<Map, Map> ctx) {
        System.out.println("Negotiate sale");
        ctx.getResponse().put("negotiateSale", "ok");
        return true;
    }

    @Override
    public String getCommandDesc() {
        return "销售谈判";
    }
}



// 安排财务
@Component
public class ArrangeFinancingCommand implements HandlerBaseCommand<Map, Map> {

    @Override
    public boolean execute(HandlerBaseContext<Map, Map> ctx) {
        System.out.println("Arrange financing");
        ctx.getResponse().put("arrangeFinancing","ok");
        return true;
    }

    @Override
    public String getCommandDesc() {
        return "安排财务";
    }
}


// 结束销售
@Component
public class CloseSaleCommand implements HandlerBaseCommand<Map, Map> {

    @Override
    public boolean execute(HandlerBaseContext<Map, Map> ctx) {
        System.out.println("Congratulations " + ctx.getRequest().get("customerName") + ", you bought a new car!");
        return true;
    }

    @Override
    public String getCommandDesc() {
        return "结束销售";
    }
}

测试:

public class ChainCarSalesTest extends BaseTest {

    @Autowired
    private ChainCarSales chainCarSales;


    @Test
    public void test() {
        HandlerBaseContext<Map, Map> context = new HandlerBaseContext<>();
        Map req = Maps.newHashMap();
        req.put("customerName", "老李");
        context.setRequest(req);
        context.setResponse(Maps.newHashMap());
        chainCarSales.execute(context);
        // 获取返回值
        Map res = context.getResponse();
        System.out.println("获取其中一个command的返回值:" + res.get("negotiateSale"));
    }
}

运行结果:

GetCustomerInfo 
2021-08-24 14:36:09.964 [main] [,] DEBUG org.example.design.chain.custom.HandlerBaseChain - 执行职责[获取客户信息]成功。耗时:1ms
Test drive the vehicle
2021-08-24 14:36:09.965 [main] [,] DEBUG org.example.design.chain.custom.HandlerBaseChain - 执行职责[试车]成功。耗时:0ms
Negotiate sale
2021-08-24 14:36:09.966 [main] [,] DEBUG org.example.design.chain.custom.HandlerBaseChain - 执行职责[销售谈判]成功。耗时:1ms
Arrange financing
2021-08-24 14:36:09.966 [main] [,] DEBUG org.example.design.chain.custom.HandlerBaseChain - 执行职责[安排财务]成功。耗时:0ms
Congratulations 老李, you bought a new car!
2021-08-24 14:36:09.966 [main] [,] DEBUG org.example.design.chain.custom.HandlerBaseChain - 执行职责[结束销售]成功。耗时:0ms
获取其中一个command的返回值:ok

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值