责任链模式

责任链模式
	利用链式处理消息
1.定义抽象类,有级别,抽象类成员变量,定义通用(设置下级)
	和(传递消息)的具体方法以及抽象的处理消息方法	
2.定义具体类继承抽象类,设置各自的级别大小,重写处理方法
3.客户端通过具体类,从级别由低到高,通过父类的设置下级的方法
	形成链式处理,使用起始类实例来传递消息

1.定义抽象类,有级别,抽象类成员变量,定义通用(设置下级)
	和(传递消息)的具体方法以及抽象的处理消息方法	
	abstract class MilitaryPosition{
		protected MilitaryPosition nextMilitaryPosition;
		protected int affairLevel;
		public void setNextPosition(MilitaryPosition
					 nextMilitaryPosition) {
			this.nextMilitaryPosition = nextMilitaryPosition;
		};
		public void receiveMessage(int level,String message) {
			if(affairLevel >= level) {
				dealAffair(message);
			}
			else if(nextMilitaryPosition != null) {
				nextMilitaryPosition.receiveMessage(level, message);
			}
		}
		public abstract void dealAffair(String message);
	}
2.定义具体类继承抽象类,设置各自的级别大小,重写处理方法
	class Soldier extends MilitaryPosition{
		@Override
		public void dealAffair(String message) {
			System.out.println("士兵可以解决:"+message);
		}
	}
	class Lieutenant extends MilitaryPosition{
		public Lieutenant() {
			affairLevel = 1;
		}
		@Override
		public void dealAffair(String message) {
			System.out.println("少尉可以解决:"+message);
		}
		
	}
	class Major extends MilitaryPosition{
		public Major() {
			affairLevel = 2;
		}
		@Override
		public void dealAffair(String message) {
			System.out.println("将军可以解决:"+message);
		}
	}
3.客户端通过具体类,从级别由低到高,通过父类的设置下级的方法
	形成链式处理,使用起始类实例来传递消息
	public static void main(String[] args) {
		MilitaryPosition militaryPosition = new Soldier();
		MilitaryPosition lieutenant = new Lieutenant();
		MilitaryPosition major = new Major();
		militaryPosition.setNextPosition(lieutenant);
		lieutenant.setNextPosition(major);
		militaryPosition.receiveMessage(0, "做饭");
		militaryPosition.receiveMessage(2, "买武器");
		militaryPosition.receiveMessage(1, "训练士兵");
	}			
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值