更多的可以参考我的博客,也在陆续更新ing
http://www.hspweb.cn/
命令模式:将“请求”封装成,对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
下面例子为:音乐播放器的操作有:播放、上一首、下一首、暂停等功能,请用命令模式对该播放器的上述功能进行设计。
1.目录
image2.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();
}
}
网友评论