JAVA化境(十二)设计模式之责任链设计模式

前言

     本章讲解设计模式中责任链设计模式的相关知识

方法

1.概念

试想下面的场景:某公司审批财务拨款购买设备,小于10万元的货物由主任批示,大于10万且小于100万的货物由经理批示,大于100万的货物由总经理批示。那么如何实现这个逻辑呢?

那么我们首先想到的就是使用传统的if...else来进行处理,但是对于业务复杂和维护来说都是相当的困难。

为了解决上面提到的问题,我们使用责任链模式来更好的处理财务审批的环节。

2.责任链设计模式的实现思路

1)创建对应工程

2)编写申请表类

package chain;

/**
 * 申请表
 * @author jwang
 *
 */
public class Apply {
	private String name;
	private int money;//以万为单位
	public Apply(String name, int money) {
		super();
		this.name = name;
		this.money = money;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getMoney() {
		return money;
	}
	public void setMoney(int money) {
		this.money = money;
	}
	
}

3)创建责任链抽象类

package chain;

/**
 * 责任链抽象类
 * @author jwang
 *
 */
public abstract class Leader {
	protected String name;
	protected Leader nextLeader;//下一个领导
	
	public Leader(String name) {
		super();
		this.name = name;
	}

	public void setNextLeader(Leader nextLeader) {
		this.nextLeader = nextLeader;
	}
	//处理申请
	public abstract void handleRequest(Apply apply);
}

4)创建责任链具体的领导类(主任、经理、总经理)

package chain;

/**
 * 主任
 * @author jwang
 *
 */
public class Director extends Leader {

	public Director(String name) {
		super(name);
	}

	@Override
	public void handleRequest(Apply apply) {
		if(apply.getMoney()<10){
			System.out.println("审批金额小于10万,"+this.name+"审批通过!");
		}else {
			//交给下一个领导审批
			this.nextLeader.handleRequest(apply);
		}
	}

}
package chain;
/**
 * 经理
 * @author jwang
 *
 */
public class Manager extends Leader {

	public Manager(String name) {
		super(name);
	}

	@Override
	public void handleRequest(Apply apply) {
		if(apply.getMoney()<100){
			System.out.println("审批金额小于100万,"+this.name+"审批通过!");
		}else {
			//交给下一个领导审批
			this.nextLeader.handleRequest(apply);
		}
	}

}
package chain;
/**
 * 总经理
 * @author jwang
 *
 */
public class GeneralManager extends Leader {

	public GeneralManager(String name) {
		super(name);
	}

	@Override
	public void handleRequest(Apply apply) {
		if(apply.getMoney()>100){
			System.out.println("审批金额大于100万,"+this.name+"审批通过!");
		}
	}

}

5)编写代码进行测试

package chain;

public class Test {

	public static void main(String[] args) {
		Apply apply1 = new Apply("材料费申请", 90);
        Apply apply2 = new Apply("材料费申请", 120);
		
		Leader a = new Director("张主任");
		Leader b = new Manager("李经理");
		Leader c = new GeneralManager("王总经理");
		
        //设置领导顺序
		a.setNextLeader(b);
		b.setNextLeader(c);
		
		a.handleRequest(apply1);
        a.handleRequest(apply2);
	}

}

程序运行结果为:

猜你喜欢

转载自blog.csdn.net/qq_21046965/article/details/92401100