Chain Of Responsibility-----设计模式

1.责任链,首先存在一个责任链,有一个问题,下面开始解决这个问题。从责任链的第一个节点开始来解决这个问题,如果这个节点不能解决,那么用下一个节点来解决,如果整个责任链都没有可以解决该问题的方法,那么就failed。

2.这个模式比较简单明了,下面是一个例子:


package com.cn;

class Trouble {
	private int number;
	public Trouble(int number) {
		this.number = number;
	}
	public int getNumber() {
		return number;
	}
	public String toString() {
		return "[Trouble " + number + "]";
	}
}



abstract class Support {
	private String name;
	private Support next;
	public Support(String name) {
		this.name = name;
	}
	public Support setSupport(Support next) {
		this.next = next;
		return next;
	}
	public final void support(Trouble trouble) {
		if (resolve(trouble)) {
			done(trouble);
		}
		else if (next != null) {
			next.support(trouble);
		}
		else {
			fail(trouble);
		}
	}
	
	public String toString() {
		return "[" + name + "]";
	}
	protected abstract boolean resolve(Trouble trouble);
	protected void done(Trouble trouble) {
		System.out.println(trouble + "is resolved by" + this + ".");
	}
	protected void fail(Trouble trouble) {
		System.out.println(trouble + "cannot be resovled.");
	}
}



class NoSupport extends Support {
	public NoSupport(String name) {
		super(name);
	}
	protected boolean resolve(Trouble trouble) {
		return false;
	}
}


class LimitSupport extends Support {
	private int limit;
	public LimitSupport(String name, int limit) {
		super(name);
		this.limit = limit;
	}
	protected boolean resolve(Trouble trouble) {
		if (trouble.getNumber() < limit) {
			return true;
		}
		else {
			return false;
		}
	}
}


class OddSupport extends Support {
	public OddSupport(String name) {
		super(name);
	}
	protected boolean resolve(Trouble trouble) {
		if (trouble.getNumber() % 2 == 1) {
			return true;
		}
		else {
			return false;
		}
	}
}



class SpecialSupport extends Support {
	private int number;
	public SpecialSupport(String name, int number) {
		super(name);
		this.number = number;
	}
	protected boolean resolve(Trouble trouble) {
		if(trouble.getNumber() == number) {
			return true;
		}
		else {
			return false;
		}
	}
}

public class Main {
	public static void main(String[] args) {
		Support alice = new NoSupport("Alice");
		Support bob = new LimitSupport("Bob",100);
		Support charlie = new SpecialSupport("Charlie",429);
		Support diana = new LimitSupport("Diana",200);
		Support elmo = new OddSupport("Elmo");
		Support fred = new LimitSupport("Fred",300);
		//create the chain of responsibility
		alice.setSupport(bob).setSupport(charlie).setSupport(diana).setSupport(elmo).setSupport(fred);
		for (int i = 0; i < 500; i += 33) {
			alice.support(new Trouble(i));
		}
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值