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

package org.example.design.chain.custom;

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

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

    public HandlerBaseChain() {
    }

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

    /**
     *
     * @param context
     * @return true表示可以执行下一个command
     */
    public boolean execute(HandlerBaseContext 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 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 {
    boolean execute(HandlerBaseContext var1);

    String getCommandDesc();
}


import java.beans.ConstructorProperties;

public class HandlerBaseContext {
    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 {

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

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



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

    @Override
    public boolean execute(HandlerBaseContext 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 {

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

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



// 安排财务
@Component
public class ArrangeFinancingCommand implements HandlerBaseCommand {

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

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


// 结束销售
@Component
public class CloseSaleCommand implements HandlerBaseCommand {

    @Override
    public boolean execute(HandlerBaseContext 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 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

你可能感兴趣的:(设计模式)