国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

java設計模式之命令模式

2019-11-14 09:56:48
字體:
來源:轉載
供稿:網友

命令模式:將“請求”封裝成對象,以便使用不同的請求、隊列或者日志來參數化其他對象。命令模式也支持可撤銷的操作。

命令模式類圖: 這里寫圖片描述 下面我們來用命令模式來實現控制燈的開關。 類圖: 這里寫圖片描述 RemoteLoader來下發開/關燈的命令,RemoteControl來設置要調用的接口是LightOnCommand/LightOffCommand,最后由Light對象來實現具體的命令。

Light類代碼實現:

public class Light { public void on(){ System.out.Command接口代碼實現:

public interface Command { public void execute(); public void undo();}

LightOnCommand類代碼實現:

public class LightOnCommand implements Command{ Light light; public LightOnCommand(Light light){ this.light = light; } @Override public void execute() { // TODO Auto-generated method stub light.on(); } @Override public void undo() { // TODO Auto-generated method stub light.off(); }}

LightOffCommand類代碼實現:

public class LightOffCommand implements Command{ Light light; public LightOffCommand(Light light){ this.light = light; } @Override public void execute() { // TODO Auto-generated method stub light.off(); } @Override public void undo() { // TODO Auto-generated method stub light.on(); }}

RemoteControl類代碼實現:

public class RemoteControl { Command command; public void setCommand(Command command){ this.command = command; } public void buttonW
aspushed(){ command.execute(); } public void undoButtonWasPushed(){ command.undo(); }}

RemoteLoader類代碼實現:

public class RemoteLoader { public static void main(String[] args){ Light light = new Light(); Command lightOnCommand = new LightOnCommand(light); Command lightOffCommand = new LightOffCommand(light); RemoteControl remoteControl = new RemoteControl(); remoteControl.setCommand(lightOnCommand); remoteControl.buttonWasPushed(); remoteControl.undoButtonWasPushed(); remoteControl.setCommand(lightOffCommand); remoteControl.buttonWasPushed(); remoteControl.undoButtonWasPushed(); }}

運行結果:

turn light onturn light offturn light offturn light on
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 旌德县| 太谷县| 望城县| 宜兰县| 高青县| 光泽县| 来宾市| 新巴尔虎右旗| 张家港市| 黄骅市| 靖远县| 汉川市| 三明市| 襄樊市| 绩溪县| 浮山县| 丹寨县| 西昌市| 安溪县| 专栏| 金乡县| 五指山市| 江陵县| 南投县| 尚志市| 盖州市| 乐安县| 达拉特旗| 古丈县| 武山县| 东城区| 和龙市| 松溪县| 农安县| 宕昌县| 合川市| 蕲春县| 临夏市| 新晃| 额敏县| 游戏|