你应该在这里使用command 模式。通常它有 Invoker、Client、Command 和 Receiver。以下是您可能需要的课程。
命令
public interface ICommand {
void execute();
}
调用者
public class RemoteControl {
Map<Key, ICommand> commandsByKey;
public RemoteControl() {
commandsByKey = new HashMap<>();
}
public void setCommand(Key key, ICommand command) {
commandsByKey.put(key, command);
}
public void press(Key key) throws Exception {
ICommand command = commandsByKey.get(key);
if(command == null)
throw new Exception("Invalid Key");
command.execute();
}
}
接收者
public class TV {
private String brand;
public TV(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return brand + " TV";
}
}
客户
public abstract class Place {
private TV tv;
private RemoteControl remoteControl;
public Place(TV tv) {
this.tv = tv;
this.remoteControl = new RemoteControl();
remoteControl.setCommand(Key.UP, new UpCommand(this.tv));
remoteControl.setCommand(Key.FORWARD, new ForwardCommand(this.tv));
remoteControl.setCommand(Key.DOWN, new DownCommand(this.tv));
remoteControl.setCommand(Key.BACK, new BackCommand(this.tv));
}
public TV getTv() {
return tv;
}
public RemoteControl getRemoteControl() {
return remoteControl;
}
}
public class Home extends Place {
public Home() {
super(new TV("Sony"));
}
}
public class Hotel extends Place {
public Hotel() {
super(new TV("LG"));
}
}
具体命令
public class UpCommand implements ICommand {
private TV tv;
public UpCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
System.out.println("Up Command - " + tv);
}
}
public class DownCommand implements ICommand {
private TV tv;
public DownCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
System.out.println("Down Command - " + tv);
}
}
public class ForwardCommand implements ICommand {
private TV tv;
public ForwardCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
System.out.println("Forward Command - " + tv);
}
}
public class BackCommand implements ICommand {
private TV tv;
public BackCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
System.out.println("Back Command - " + tv);
}
}
按键
public enum Key {
UP, DOWN, FORWARD, BACK
}
测试
public class RemoteTest {
public static void main(String[] args) throws Exception {
Place home = new Home();
home.getRemoteControl().press(Key.UP);
home.getRemoteControl().press(Key.DOWN);
home.getRemoteControl().press(Key.BACK);
Hotel hotel = new Hotel();
hotel.getRemoteControl().press(Key.UP);
}
}
如果您向遥控器添加任何其他键,则无需触摸任何现有命令或调用程序。您只需要在客户端中添加它。这遵守Open Close principle。如果每个地方都有不同的遥控器,则将其作为构造函数参数,因此您无需更改任何其他类。