欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

责任链模式

程序员文章站 2022-05-24 08:42:44
...
类:beater 击鼓者
package beat;

import java.util.Timer;
import java.util.TimerTask;

public class Beater {
	public static boolean stopped = false;
	private static Player firstPlayer = null;
	private Timer timer;

	class Task extends TimerTask {
		public void run() {
			stopped = true;
			System.out.println("鼓声已停");
		}
	}

	public void startBeating(int seconds) {
		timer = new Timer();
		System.out.println("开始击鼓");
		timer.schedule(new Task(), seconds);
	}

	public static void main(String[] args) {
		Beater beater = new Beater();
	    PlayerA A = new PlayerA(null);
	    A.setSuccessoer(new PlayerB(new PlayerC(new PlayerD(A))));
	    beater.startBeating(2);//计时的时间为2秒
	    firstPlayer=A;//从A开始
	    A.handle();
	}

}
抽象类:Player

package beat;

public abstract class Player {
private Player successor;
public abstract void handle();
public Player(){
	successor = null;
}
protected void setSuccessoer(Player successor){
	this.successor = successor;
}
public void next(){
	if(successor!=null){
		successor.handle();
	}else{
		System.out.println("没有下一个接替者了");
		System.exit(0);
	}
}
}

具体类:PlayerA
package beat;

public class PlayerA extends Player {
	public PlayerA(Player successor){
		this.setSuccessoer(successor);
	}
	@Override
	public void handle() {
	if(Beater.stopped){
		System.out.println("A must have a drink");
	}else{
		System.out.println("A just passed");
		next();
	}

	}

}
//以下的PlayerB,PlayerC,PlayerD省略了