java学习-设计模式-职责链模式
Posted 菜鸟码农的学习历程
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java学习-设计模式-职责链模式相关的知识,希望对你有一定的参考价值。
二十:chain of responsibility
需求
公司请假,加薪,权限不够,向上级请示。
代码实现
请求类:
public class Request {
private String requestType;
private String requestContent;
private int number;
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getRequestContent() {
return requestContent;
}
public void setRequestContent(String requestContent) {
this.requestContent = requestContent;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
抽象管理类:
public abstract class Manager {
private String name;
private Manager superior;
public Manager(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Manager getSuperior() {
return superior;
}
public void setSuperior(Manager superior) {
this.superior = superior;
}
public abstract void requestApplications(Request request);
}
经理类:
public class CommonManager extends Manager {
public CommonManager(String name) {
super(name);
}
@Override
public void requestApplications(Request request) {
if ("请假".equals(request.getRequestType()) && request.getNumber() <= 2) {
System.out.println(super.getName() + ":同意" + request.getRequestContent() + "数量为" + request.getNumber() + "天");
} else {
if (super.getSuperior() != null) {
super.getSuperior().requestApplications(request);
}
}
}
}
总监类:
public class Majordomo extends Manager {
public Majordomo(String name) {
super(name);
}
@Override
public void requestApplications(Request request) {
if ("请假".equals(request.getRequestType()) && request.getNumber() <= 5) {
System.out.println(super.getName() + ":同意" + request.getRequestContent() + "数量为" + request.getNumber() + "天");
} else {
if (super.getSuperior() != null) {
super.getSuperior().requestApplications(request);
}
}
}
}
总经理类:
public class GeneralManager extends Manager {
public GeneralManager(String name) {
super(name);
}
@Override
public void requestApplications(Request request) {
if ("请假".equals(request.getRequestType())) {
System.out.println(super.getName() + ":同意" + request.getRequestContent() + "数量为" + request.getNumber() + "天");
} else if ("加薪".equals(request.getRequestType()) && request.getNumber() <= 500) {
System.out.println(super.getName() + ":同意" + request.getRequestContent() + "数量为" + request.getNumber() + "元");
} else if ("加薪".equals(request.getRequestType()) && request.getNumber() > 500){
System.out.println(super.getName() + ":再说吧," + request.getRequestContent() + "数量为" + request.getNumber() + "元");
}
}
}
职责链模式:
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为之。
以上是关于java学习-设计模式-职责链模式的主要内容,如果未能解决你的问题,请参考以下文章