public class Param {
double number;
public double getNumber() {
return number;
}
public void setNumber(double number) {
this.number = number;
}
}
public class Result {
private double result;
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
}
public abstract class FeeCalcHandler {
protected FeeCalcHandler nextHandler;
abstract Result calc(Param param);
}
public class NewFeeCalcHandler extends FeeCalcHandler{
@Override
Result calc(Param param) {
Result result = new Result();
if(nextHandler != null){
result= nextHandler.calc(param);
}
result.setResult(param.getNumber() + 1);
return result;
}
}
public class VIPFeeCalcHandler extends FeeCalcHandler{
@Override
Result calc(Param param) {
Result result = new Result();
if(nextHandler != null){
result = nextHandler.calc(param);
}
result.setResult(param.getNumber() * 10);
return result;
}
}
public class InitFeeCalcHandler {
private HandlerNode handlerNode = new HandlerNode();
InitFeeCalcHandler addLeft(FeeCalcHandler handler){
handlerNode.addLeft(new HandlerNode(handler));
return this;
}
InitFeeCalcHandler addRight(FeeCalcHandler handler){
handlerNode.addRight(new HandlerNode(handler));
return this;
}
public Result calc(Param param) {
return handlerNode.handler.calc(param);
}
public void getAll(Consumer<HandlerNode> consumer){
HandlerNode temp = handlerNode;
while (temp != null){
consumer.accept(temp);
temp = temp.next;
}
}
class HandlerNode{
HandlerNode next;
FeeCalcHandler handler;
public HandlerNode(){}
private HandlerNode(FeeCalcHandler leaveHandler){
this.handler = leaveHandler;
}
public void addRight(HandlerNode node){
if(handlerNode.handler == null){
handlerNode = node;
return;
}
HandlerNode tailNode = getTail(handlerNode);
tailNode.handler.nextHandler= node.handler;
tailNode.next = node;
}
public HandlerNode getTail(HandlerNode node){
if(node.next == null || node.next.handler == null){
return node;
}
return getTail(node.next);
}
public void addLeft(HandlerNode node){
if(handlerNode.handler == null){
handlerNode = node;
return;
}
HandlerNode temp = handlerNode;
handlerNode = node;
handlerNode.next = temp;
handlerNode.handler.nextHandler = temp.handler;
}
}
}
public class HandlerV2Test {
public static void main(String[] args) {
Param param = new Param();
param.setNumber(100);
InitFeeCalcHandler initFeeCalcHandler = new InitFeeCalcHandler();
initFeeCalcHandler
.addRight(new NewFeeCalcHandler())
.addRight(new VIPFeeCalcHandler());
Result result = initFeeCalcHandler.calc(param);
System.out.println(result.getResult());
}
}
欢迎小伙伴一起探讨设计模式
请大家关注下博客谢谢
源码已经提交到码云 https://gitee.com/tianji_luhaichuan/pay/tree/master/java-base