标签:模式 set public print top interface ace src rgs
命令模式:
对命令的封装,把发出命令的责任和执行命令的责任分割开,委派给不同的对象。
命令模式涉及到五个角色:
录音机类:
/** * 具体工作的类(录音机) */ public class AudioPlayer { public void play() { System.out.println("播放..."); } public void rewind() { System.out.println("倒带..."); } public void stop() { System.out.println("停止播放..."); } }
命令接口:
/** * 执行录音机的命令 */ public interface Command { public void execute(); }
播放命令:
/** * 播放命令 */ public class PlayCommand implements Command { private AudioPlayer audioPlayer; public PlayCommand(AudioPlayer audioPlayer) { this.audioPlayer = audioPlayer; } @Override public void execute() { audioPlayer.play(); } }
倒带命令:
/** * 倒带命令 */ public class RewindCommand implements Command { private AudioPlayer audioPlayer; public RewindCommand(AudioPlayer audioPlayer) { this.audioPlayer = audioPlayer; } @Override public void execute() { audioPlayer.rewind(); } }
停止命令:
/** * 停止命令 */ public class StopCommand implements Command { private AudioPlayer audioPlayer; public StopCommand(AudioPlayer audioPlayer) { this.audioPlayer = audioPlayer; } @Override public void execute() { audioPlayer.stop(); } }
按键类:
** * 按键类 */ public class Keypad { private Command playCommand; private Command rewindCommand; private Command stopCommand; public void setPlayCommand(Command playCommand) { this.playCommand = playCommand; } public void setRewindCommand(Command rewindCommand) { this.rewindCommand = rewindCommand; } public void setStopCommand(Command stopCommand) { this.stopCommand = stopCommand; } /** * 执行播放 */ public void pay() { playCommand.execute(); } /** * 执行倒带 */ public void rewind() { rewindCommand.execute(); } /** * 执行停止 */ public void stop() { stopCommand.execute(); } }
录音机操作类:
/** * 操作按钮-》发送命令给录音机执行具体操作 */ public class CommandMain { public static void main(String[] args) { //new 一个录音机 AudioPlayer audioPlayer = new AudioPlayer(); //创建播放命令对象 Command playCommand = new PlayCommand(audioPlayer); //创建倒带命令对象 Command rewindCommand = new RewindCommand(audioPlayer); //创建停止命令对象 Command stopCommand = new StopCommand(audioPlayer); //创建按键对象 Keypad keypad = new Keypad(); //将播放命令绑定在按键上 keypad.setPlayCommand(playCommand); //将倒带命令绑定在按键上 keypad.setRewindCommand(rewindCommand); //将停止命令绑定在按键上 keypad.setStopCommand(stopCommand); //播放 keypad.pay(); //倒带 keypad.rewind(); //停止 keypad.stop(); keypad.pay(); keypad.stop(); } }
运行结果:
标签:模式 set public print top interface ace src rgs
原文地址:https://www.cnblogs.com/hujinshui/p/9451984.html