设计模式(一):责任链学习

关于责任链的学习,具体参考代码
最关键点就是面向接口的编程思想
抽象类Manager:setSuperior(manager) 设置上级
抽象方法handler(requets)
由具体的子类去实现,根据不同的权限
这种设计模式优点:
1. 解除耦合
2. 容易扩展,比如增加ceo具体类,只要实现有关的handler方法和上下级,就可以使用了

以上的知识点来自"大话设计模式"一书。


package reponsibilitylink;

/**
* 责任链
* 1. 抽象经理,
* abstract void hanler(request),
* setSuperior()设置上级
* 2. 具体经理类
* 小组长:
* 设置上级
* 逻辑处理方法hanller()
* 具体权限设置,如果请求类型和内容符合,则处理
* 总经理:
* 设置上级
* 逻辑处理方法hanller()
* 如果请求类型和内容符合,则处理
* 3. 请求实体类
* type, content
* 4.
* @author root
*
*/
public class Client {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GeneralManager general = new GeneralManager("generalmanager");
TeamLeader teamLeader = new TeamLeader("teamleader");
teamLeader.setSuperior(general);

Request request = new Request();
request.setType(1);
request.setContent("病假");
teamLeader.handle(request);

request = new Request();
request.setType(2);
request.setContent("加薪");
teamLeader.handle(request);

}

}



package reponsibilitylink;

public abstract class Manager {

Manager superior;
private String name;

public Manager(String name){
this.name = name;
}

public void setSuperior(Manager superior){
this.superior = superior;
}

protected abstract void handle(Request request);
}



package reponsibilitylink;

public class Request {
int type;
String content;

public int getType() {
return type;
}

public void setType(int type) {
this.type = type;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

}

[code="java"]
package reponsibilitylink;

public class TeamLeader extends Manager {

public TeamLeader(String name) {
super(name);
// TODO Auto-generated constructor stub
}

protected void handle(Request request) {
// TODO Auto-generated method stub
if(request.getType()==1){
System.out.println("同意: " + request.content);
}else{
if(superior!=null){
superior.handle(request);
}
}
}

}




package reponsibilitylink;

public class GeneralManager extends Manager {

public GeneralManager(String name) {
super(name);
// TODO Auto-generated constructor stub
}

@Override
protected void handle(Request request) {
// TODO Auto-generated method stub
if(request.getType()>1){
System.out.println("总经理批准 请求: " + request.getContent());
}
}

}


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