责任链模式
利用链式处理消息
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, "训练士兵");
}
责任链模式
最新推荐文章于 2021-01-26 14:45:00 发布