Head First设计模式(6):命令模式

更多的可以参考我的博客,也在陆续更新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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容