今天来讲一个悲伤的故事,关于小明找小红的故事。加班狗小明某日不用加班,开开心心把家还,结果妻子小红不在家,发生了下面的一幕:
上代码。首先定义好小红
public interface Lover {
}
小红:
public class WifeHong implements Lover {
public WifeHong(Affairs affairs) {
System.out.println("我是小红,去" + affairs.name + "家。");
affairs.setLover(this);
}
}
处理请求抽象类:
public abstract class Affairs {
protected Affairs nextOne;
protected String name;
protected Lover lover;
protected Affairs(String name) {
this.name = name;
}
public abstract void handleRequest(Lover lover);
public void setLover(Lover lover) {
this.lover = lover;
}
public void setNextOne(Affairs nextOne) {
this.nextOne = nextOne;
}
public Affairs getNextOne() {
return nextOne;
}
}
具体处理请求类:
public class OldMan extends Affairs {
public OldMan(String name) {
super(name);
}
@Override
public void handleRequest(Lover _lover) {
System.out.println("==============================");
System.out.println("咚咚咚... " + name + " ,我来找小红。");
if (lover == null)
System.out.println("[" + name + "]我不认识,走开。");
else if (lover.equals(_lover))
System.out.println("[" + name + "]pia pia pia...");
if (nextOne == null)
System.out.println("[" + name + "]回家吧,小明,听大哥的话。");
else {
System.out.println("[" + name + "]去别人家找去,跟我没关系。");
nextOne.handleRequest(_lover);
}
}
}
请求者小明:
public class XiaoMing {
public static void main(String[] args) {
OldMan oldLi = new OldMan("老李");
OldMan oldZhou = new OldMan("老周");
OldMan oldWang = new OldMan("老王");
Lover xiaoHong = new WifeHong(oldWang);
oldLi.setNextOne(oldZhou);
oldZhou.setNextOne(oldWang);
oldLi.handleRequest(xiaoHong);
}
}
执行结果,真相大白:
后话:关于责任链,就在于这个handleRequest方法,其他东西都是情节需要,自行演绎。(^_^)