命令模式(Command)_java实现

//20210129
写在前面:刚期末考试完,考了面向对象,里边儿有23个设计模式,我寻思着考完挨个儿实现一下,本文实现命令模式

命令模式核心思想:

  • 将操作封装成一个对象,请求者发送请求给包装有命令的接受者,然后接受者执行相应操作,用户不需要知道操作如何执行的,只需要发送请求即可

程序源代码

  • 此处便于理解,实现一个收音机的例子,收音机有键盘,有具体命令操作,有执行操作系统,键盘作为请求者发送请求给接受者,接受者作出相应操作
/**
 * 播放器所包含的功能 ————具体操作
 */
public class AudioPlayer {
    public void play(){
        System.out.println("播放...");

    }
    public void rewind(){
        System.out.println("倒带...");

    }
    public void stop(){
        System.out.println("停止...");

    }
}

/**
 * 抽象命令接口
 */
public interface Command {
    //执行方法
    void execute();
}


/**
 * 实现播放命令类
 */
public class PlayCommand implements Command{
    private AudioPlayer audioPlayer = null;

    public PlayCommand(AudioPlayer audioPlayer){
        this.audioPlayer = audioPlayer;
    }

    @Override
    public void execute() {
        audioPlayer.play();
    }
}

/**
 * 倒带命令实现类
 */
public class RewindCommand implements Command{
    private AudioPlayer audioPlayer = null;

    public RewindCommand(AudioPlayer audioPlayer){
        this.audioPlayer = audioPlayer;
    }

    @Override
    public void execute() {
        audioPlayer.rewind();
    }
}


/**
 * 停止命令实现类
 */
public class StopCommand implements Command{
    private AudioPlayer audioPlayer = null;

    public StopCommand(AudioPlayer audioPlayer){
        this.audioPlayer = audioPlayer;
    }

    @Override
    public void execute() {
        audioPlayer.stop();
    }
}

/**
 * 请求者
 */
public class Keyboard {
    private Command playCommand = null;
    private Command rewindCommand = null;
    private Command stopCommand = null;

    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 play(){
        playCommand.execute();
    }
    //执行倒带方法
    public void reWind(){
        rewindCommand.execute();
    }
    //执行停止播放方法
    public void stop() {
        stopCommand.execute();
    }
}

/**
 * 测试主类
 */
public class Main {
    public static void main(String[] args) {
        AudioPlayer audioPlayer = new AudioPlayer();
        Keyboard keyBoard = new Keyboard();
        keyBoard.setPlayCommand(new PlayCommand(audioPlayer));
        keyBoard.setRewindCommand(new RewindCommand(audioPlayer));
        keyBoard.setStopCommand(new StopCommand(audioPlayer));

        keyBoard.play();
        keyBoard.reWind();
        keyBoard.stop();
        keyBoard.reWind();
        keyBoard.stop();
    }
}

  • 输出如下:

以上
希望对大家有所帮助

原文地址:https://www.cnblogs.com/lavender-pansy/p/14346883.html