更多的可以參考我的博客,也在陸續(xù)更新ing
http://www.hspweb.cn/
命令模式:將“請(qǐng)求”封裝成环形,對(duì)象总寻,以便使用不同的請(qǐng)求、隊(duì)列或者日志來(lái)參數(shù)化其他對(duì)象犹褒。命令模式也支持可撤銷的操作抵窒。
下面例子為:音樂(lè)播放器的操作有:播放、上一首叠骑、下一首李皇、暫停等功能,請(qǐng)用命令模式對(duì)該播放器的上述功能進(jìn)行設(shè)計(jì)宙枷。
1.目錄
image
2.package command
①.Command.java
package command;
//實(shí)現(xiàn)命令接口
public interface Command {
public void excute();
}
②.PlaySongCommand.java
package command;
import manufacturer.Player;
//實(shí)現(xiàn)一個(gè)播放器播放的命令
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;
//簡(jiǎn)單的遙控器
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("開(kāi)始播放音樂(lè)");
}
public void stop(){
System.out.println("停止播放音樂(lè)");
}
public void nextSong(){
System.out.println("播放下一首音樂(lè)");
}
public void preSong(){
System.out.println("播放上一首音樂(lè)");
}
}
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();
}
}
補(bǔ)充類圖
image