/**
* 命令模式:将方法的请求者跟方法的实现者进行分开,常见的例子:遥控器(命令发送者Invoker) 通过按钮(具体的命令Command) 来操作电视机(Receiver 命令接收者或者说是命令实现者)
* 这样做的话,方法的请求者(遥控器)跟实现者(电视机)就分开了,解耦合了
*
*
*/
//创建遥控器(命令发送者Invoker)
public class RemoteControl {
//具体的命令Command
private IButton openButton;
private IButton closeButton;
public IButton getOpenButton() {
return openButton;
}
public void setOpenButton(IButton openButton) {
this.openButton = openButton;
}
public IButton getCloseButton() {
return closeButton;
}
public void setCloseButton(IButton closeButton) {
this.closeButton = closeButton;
}
public void openTV(){
openButton.action();
}
public void closeTV(){
closeButton.action();
}
}
//命令
public interface IButton {
void action();
}
//关闭命令
public class CloseButton implements IButton {
private TV tv;
public CloseButton(TV tv) {
this.tv = tv;
}
@Override
public void action() {
tv.close();
}
}
//开关按钮
public class OpenButton implements IButton {
//Receiver 命令接收者或者说是命令实现者
private TV tv;
public OpenButton(TV tv) {
this.tv = tv;
}
@Override
public void action() {
tv.open();
}
}
//Receiver 命令接收者或者说是命令实现者
public class TV {
public void open(){
System.out.println("开电视机");
}
public void close(){
System.out.println("关电视机");
}
}
public class Test {
public static void main(String[] args) {
//创建调用者遥控器
RemoteControl remoteControl = new RemoteControl();
//创建接收者TV
TV tv = new TV();
//创建开机按钮
IButton openButton = new OpenButton(tv);
//创建关机按钮
IButton closeButton = new CloseButton(tv);
//绑定按钮
remoteControl.setCloseButton(closeButton);
remoteControl.setOpenButton(openButton);
//开机
remoteControl.openTV();
//关机
remoteControl.closeTV();
}
}