lambda表达式之命令模式
命令接口:
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)