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

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

java設計模式之命令模式

2019-11-14 10:07:38
字體:
來源:轉載
供稿:網友

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

命令模式類圖: 這里寫圖片描述 下面我們來用命令模式來實現控制燈的開關。 類圖: 這里寫圖片描述 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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东明县| 呼和浩特市| 昌吉市| 五原县| 山东省| 景宁| 定结县| 丽江市| 伽师县| 定远县| 开封县| 江油市| 富川| 金平| 广东省| 稻城县| 茌平县| 桐乡市| 昂仁县| 大宁县| 思南县| 绍兴市| 荥阳市| 漯河市| 南城县| 剑阁县| 布拖县| 奉节县| 南岸区| 蒙山县| 广元市| 连江县| 商都县| 泸西县| 全南县| 正宁县| 大埔区| 沙河市| 二连浩特市| 仙游县| 台中市|