职责链设计模式最简单的实例

  啥是职责链设计模式、类图长啥样、有哪些应用场景等等这些网上一捞一大把,就不再费口水了。一图抵千言,一个例子抵一百个类图。不废话,上例子:

  1、职责接口:

package com.wlf.chain;

import com.wlf.entity.CommonRequest;
import com.wlf.entity.CommonResponse;

/**
 * 职责类
 */
public interface Responsibility {
    void execute(CommonRequest request, CommonResponse response, ResponsibilityChain chain);
}

 

  2、两个实现类:

package com.wlf.chain.concrete;

import com.wlf.chain.Responsibility;
import com.wlf.chain.ResponsibilityChain;
import com.wlf.entity.CommonRequest;
import com.wlf.entity.CommonResponse;

/**
 * 转写职责类
 */
public class TransferResponsibility implements Responsibility {
    @Override
    public void execute(CommonRequest request, CommonResponse response, ResponsibilityChain chain) {
        System.out.println("开始转写前处理一下...");
        chain.doExecute(request,response);
        System.out.println("结束转写前再搞一下...");
    }
}
package com.wlf.chain.concrete;

import com.wlf.chain.Responsibility;
import com.wlf.chain.ResponsibilityChain;
import com.wlf.entity.CommonRequest;
import com.wlf.entity.CommonResponse;

/**
 * 翻译职责类
 */
public class TranslateResponsibility implements Responsibility {
    @Override
    public void execute(CommonRequest request, CommonResponse response, ResponsibilityChain chain) {
        System.out.println("开始翻译前处理一下...");
        chain.doExecute(request,response);
        System.out.println("结束翻译前再搞一下...");
    }
}

 

  3、职责链类:

package com.wlf.chain;

import com.wlf.chain.concrete.TransferResponsibility;
import com.wlf.chain.concrete.TranslateResponsibility;
import com.wlf.entity.CommonRequest;
import com.wlf.entity.CommonResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * 职责链
 */
public class ResponsibilityChain {

    // 职责链当前位置,从0开始
    private int position = 0;

    private List responsibilities = new ArrayList<>();

    ResponsibilityChain addResponsibility(Responsibility responsibility) {
        responsibilities.add(responsibility);
        return this;
    }

    public void doExecute(CommonRequest request, CommonResponse response) {

        // 递归执行职责链,把所有职责都执行完递归就结束了
        if (position < responsibilities.size()) {
            Responsibility responsibility = responsibilities.get(position++);
            responsibility.execute(request, response, this);
            return;
        }

        // 职责链结束后执行业务逻辑
        System.out.println("do business...");
    }

    public static void main(String[] args) {
        ResponsibilityChain chain = new ResponsibilityChain();
        chain.addResponsibility(new TransferResponsibility());
        chain.addResponsibility(new TranslateResponsibility());
        chain.doExecute(new CommonRequest(), new CommonResponse());
    }
}

 

  运行日志:

com.wlf.chain.ResponsibilityChain
开始转写前处理一下...
开始翻译前处理一下...
do business...
结束翻译前再搞一下...
结束转写前再搞一下...

Process finished with exit code 0

 

你可能感兴趣的:(职责链设计模式最简单的实例)