当你想要让一个以上的对象有机会能够处理某个请求的时候,就使用责任链模式。
示例—大量邮件的处理
糖果公司收到了大量的邮件,其中的分类有:Fans来的信、抱怨的信、增加业务的信、垃圾邮件。现已知当收到邮件时,邮件所属的分类。需要对不同分类进行处理。
UML图表示
责任链模式-邮件处理代码演示
处理抽象类
package Chain;
public abstract class Handler {
Handler successor;
Handler(Handler successor){
this.successor = successor;
}
abstract void handleRequest(String email);
}
垃圾邮件处理类
package Chain;
public class SpamHandler extends Handler {
SpamHandler(Handler successor) {
super(successor);
}
@Override
void handleRequest(String email) {
if (email == "spam"){
System.out.println("The Email will be delete!!");
}
else if (successor != null){
successor.handleRequest(email);
}
}
}
Fans邮件处理类
package Chain;
public class FanHandler extends Handler {
FanHandler(Handler successor) {
super(successor);
}
@Override
void handleRequest(String email) {
if (email == "fan"){
System.out.println("The Email will be send to CEO.");
}
else if (successor != null){
successor.handleRequest(email);
}
}
}
抱怨的邮件处理类
package Chain;
public class ComplaintHandler extends Handler {
ComplaintHandler(Handler successor) {
super(successor);
}
@Override
void handleRequest(String email) {
if (email == "complaint"){
System.out.println("The Email will be send to Law Department.");
}
else if (successor != null){
successor.handleRequest(email);
}
}
}
寻求新业务的邮件处理类
package Chain;
public class NewLocHandler extends Handler {
NewLocHandler(Handler successor) {
super(successor);
}
@Override
void handleRequest(String email) {
if (email == "newLoc"){
System.out.println("The Email will be send to Business Department.");
}
else if (successor != null){
successor.handleRequest(email);
}
}
}
测试代码
package Chain;
public class ChainDriver {
public static void main(String[] args) {
String[] emails = new String[]{"complaint","fan","fan","spam","complaint","newLoc","spam"};
Handler handler = new SpamHandler(new FanHandler(new ComplaintHandler(new NewLocHandler(null))));
for (String email : emails){
handler.handleRequest(email);
}
}
}
测试结果
The Email will be send to Law Department.
The Email will be send to CEO.
The Email will be send to CEO.
The Email will be delete!!
The Email will be send to Law Department.
The Email will be send to Business Department.
The Email will be delete!!
网友评论