责任链模式持有一个下级对象,并在实现方法里决定处理或交给下级处理,客户提交一个请求给责任链,无需关心在哪个节点处理了这个请求,适用于有层级的请求,Android
的事件分发的思路就是这种模式。示例如下:
public class Responsibility {
public static void main(String[] args){
Responsibility responsibility = new Responsibility();
IBuyFood boy = responsibility.new Boy();
IBuyFood father = responsibility.new Father();
IBuyFood mother = responsibility.new Mother();
IBuyFood clerk = responsibility.new Clerk();
boy.setiBuyFood(father);
father.setiBuyFood(mother);
mother.setiBuyFood(clerk);
boy.buy(120);
}
abstract class IBuyFood{
private IBuyFood iBuyFood;
public IBuyFood getiBuyFood() {
return iBuyFood;
}
public void setiBuyFood(IBuyFood iBuyFood) {
this.iBuyFood = iBuyFood;
}
public abstract void buy(int money);
}
class Boy extends IBuyFood{
@Override
public void buy(int money) {
if(getiBuyFood()!=null){
System.out.println("我想用"+money+"元买个蛋糕");
getiBuyFood().buy(money);
}else{
System.out.println("想吃个蛋糕都不知道找谁买");
}
}
}
class Father extends IBuyFood{
@Override
public void buy(int money) {
if(money<100){
System.out.println("去买吧,你老爹就这么点零花钱了");
}else{
if(getiBuyFood()!=null){
System.out.println("你爹做不了主,问你妈去");
getiBuyFood().buy(money);
}else{
System.out.println("你爹还想吃蛋糕呢,找谁买去");
}
}
}
}
class Mother extends IBuyFood{
@Override
public void buy(int money) {
if(money<200){
if(getiBuyFood()!=null){
System.out.println("去买吧,妈给你");
getiBuyFood().buy(money);
}else{
System.out.println("哪来的卖蛋糕的");
}
}else{
System.out.println("小兔崽子,又吃蛋糕");
}
}
}
class Clerk extends IBuyFood{
@Override
public void buy(int money) {
if(money>150){
System.out.println("给你蛋糕");
}else{
System.out.println("这点钱买不起蛋糕的");
}
}
}
}
网友评论