国产探花免费观看_亚洲丰满少妇自慰呻吟_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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南部县| 印江| 西盟| 宣城市| 石林| 云霄县| 磴口县| 庄河市| 锦屏县| 辽中县| 彭州市| 定西市| 山西省| 乌兰浩特市| 汝州市| 遂溪县| 石棉县| 靖西县| 盘山县| 萍乡市| 宁晋县| 高淳县| 潞城市| 平凉市| 利川市| 临潭县| 东丰县| 滨海县| 北安市| 定南县| 大方县| 板桥市| 汽车| 郑州市| 奉化市| 墨脱县| 普陀区| 云阳县| 阿坝县| 泾源县| 历史|