命令接口:
public interface Command {
public void execute();
}
接收者接口:
public interface Light {
public void on();
public void off();
}
public interface Door {
public void open();
public void close();
}
接收者:
public class LivingRoomLight implements Light{
public void on(){
System.out.println("LivingRoomLight light on.");
}
public void off(){
System.out.println("LivingRoomLight light off.");
}
}
public class KitchenLight implements Light{
public void on(){
System.out.println("KitchenLight light on.");
}
public void off(){
System.out.println("KitchenLight light off.");
}
}
public class GarageDoor implements Door{
public void open(){
System.out.println("This door is open");
}
public void close(){
System.out.println("This door is closed");
}
}
调用者:
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl(){}
public void setCommand(Command command){
this.slot = command;
}
public void buttonWasPressed(){
slot.execute();
}
}
客户端:
使用lambda表达式可以省去具体的命令者类的创建。
在setCommand时候,直接传入接口Command的execute的具体实现,execute的具体实现通过lambda表达式和接收者的动作完成。
事实上,具体创建的命令者,也就是重写了Command的execute接口。
public class RemoteControlTest {
public static void main(String[] args){
SimpleRemoteControl remote = new SimpleRemoteControl();
LivingRoomLight livingRoomLight = new LivingRoomLight();
remote.setCommand(()->livingRoomLight.on());
remote.buttonWasPressed();
KitchenLight kitchenLight = new KitchenLight();
remote.setCommand(()->kitchenLight.on());
remote.buttonWasPressed();
GarageDoor garageDoor = new GarageDoor();
remote.setCommand(()->garageDoor.open());
remote.buttonWasPressed();
}
}
测试结果:
LivingRoomLight light on.
KitchenLight light on.
This door is open