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

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

java設計模式之命令模式

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

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

命令模式類圖: 這里寫圖片描述 下面我們來用命令模式來實現控制燈的開關。 類圖: 這里寫圖片描述 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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 饶平县| 德化县| 玉山县| 曲周县| 汝南县| 利津县| 方山县| 阜阳市| 张家口市| 荆门市| 长垣县| 湛江市| 泾源县| 伊春市| 隆回县| 阿城市| 永和县| 凭祥市| 永州市| 漳州市| 呈贡县| 子洲县| 县级市| 鄂尔多斯市| 金川县| 错那县| 铅山县| 鄂州市| 江北区| 洪雅县| 景宁| 溧水县| 长海县| 巴楚县| 武山县| 甘孜县| 安康市| 华阴市| 双城市| 翼城县| 恭城|