更多的可以參考我的博客,也在陸續更新ing
http://www.hspweb.cn/
命令模式:將“請求”封裝成,對象,以便使用不同的請求、隊列或者日志來參數化其他對象。命令模式也支持可撤銷的操作。
下面例子為:音樂播放器的操作有:播放、上一首、下一首、暫停等功能,請用命令模式對該播放器的上述功能進行設計。
1.目錄
image
2.package command
①.Command.java
package command;
//實現命令接口
public interface Command {
public void excute();
}
②.PlaySongCommand.java
package command;
import manufacturer.Player;
//實現一個播放器播放的命令
public class PlaySongCommand implements Command{
Player player;
public PlaySongCommand(Player player){
this.player=player;
}
public void excute() {
// TODO Auto-generated method stub
player.start();
}
}
3. package control
①.SimpleRemoteControl.java
package control;
import command.Command;
//簡單的遙控器
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl(){}
public void setCommand (Command command){
slot=command;
}
public void buttonWasPressed(){
slot.excute();
}
}
4.package manufacturer
①.Player.java
package manufacturer;
//播放器
public class Player {
public void start() {
// TODO Auto-generated method stub
System.out.println("開始播放音樂");
}
public void stop(){
System.out.println("停止播放音樂");
}
public void nextSong(){
System.out.println("播放下一首音樂");
}
public void preSong(){
System.out.println("播放上一首音樂");
}
}
5.package test
①.test.java
package test;
import command.PlaySongCommand;
import manufacturer.Player;
import control.SimpleRemoteControl;
public class test {
public static void main(String[] args) {
SimpleRemoteControl remote=new SimpleRemoteControl();
Player player=new Player();
PlaySongCommand playsong=new PlaySongCommand(player);
remote.setCommand(playsong);
remote.buttonWasPressed();
}
}
補充類圖
image