命令模式模拟指挥官发命令java实现

命令模式模拟指挥官发命令java实现,第1张

基本描述

运行截图


代码实现

项目目录

package command.homework;
//命令接口
public interface Command {
	void execute(String name) throws Exception;
}
package command.homework;
//接收者
public class Receiver {
	public void attack(String name) {
		System.out.println(name+"进攻");
	}

    public void block(String name) {
		System.out.println(name+"堵击");
    }

    public void fakeAttach(String name) {
		System.out.println(name+"佯攻");
    }
}
package command.homework;
//进攻命令
public class CommandA implements Command {
	Receiver peopleReceiver;
	public CommandA(Receiver peopleReceiver) {
		this.peopleReceiver = peopleReceiver;
	}
	@Override
	public void execute(String name) throws Exception {
		peopleReceiver.attack(name);
	}
}

package command.homework;
//block命令
public class CommandB implements Command {
	Receiver peopleReceiver;
	public CommandB(Receiver peopleReceiver) {
		this.peopleReceiver = peopleReceiver;
	}
	@Override
	public void execute(String name) throws Exception {
		peopleReceiver.block(name);
	}
}

package command.homework;
//block命令
public class CommandC implements Command {
	Receiver peopleReceiver;
	public CommandC(Receiver peopleReceiver) {
		this.peopleReceiver = peopleReceiver;
	}
	@Override
	public void execute(String name) throws Exception {
		peopleReceiver.fakeAttach(name);
	}
}

package command.homework;
public class TestUse {
	public static void main(String args[]) throws Exception{
		//接收者
		Receiver rec = new Receiver();
		//命令
		CommandA createA = new CommandA(rec);
		CommandB createB = new CommandB(rec);
		CommandC createC = new CommandC(rec);
		//请求者
		Client client = new Client();
		//执行命令
		client.setCommand(createA).executeCommand("独立团");
		client.setCommand(createB).executeCommand("三团");
		client.setCommand(createC).executeCommand("独立营");
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/800055.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存