使用命令模式实现播放器功能
我们平时使用的视频播放器都会有播放控制条,主要用来播放、拖动进度、停止播放和暂停等。我们在操作播放器的时候并不是直接调用播放器的方法,而是通过一个控制条去传达指令给播放器内核。具体传达的指令会被封装为一个个按钮,每个按钮就相当于对一条命令的封装。而用控制条也实现了用户发送指令与播放器内核接收指令的解耦。
下面来看具体实现代码,首先创建播放器内核 VideoPlayer类。
下面来看具体实现代码,首先创建播放器内核 VideoPlayer类。
public class VideoPlayer{
public void play() {
System.out.println("正常播放");
}
public void speed() {
System.out.println("拖动进度条");
}
public void stop() {
System.out.println("停止播放");
}
public void pause() {
System.out.println("暂停播放");
}
}
创建命令接口 Command 类。
public interface Command {
void execute();
}
然后分别创建操作播放器可以接收的指令,播放指令 PlayCommand 类的代码如下。
public class PlayCommand implements Command {
private VideoPlayer videoPlayer;
public PlayCommand(VideoPlayer videoPlayer ) {
this.videoPlayer = videoPlayer ;
}
@Override
public void execute() {
videoPlayer.play();
}
}
暂停指令 PauseCommand 类的代码如下。
public class PauseCommand implements Command {
private VideoPlayer videoPlayer;
public PauseCommand(VideoPlayer videoPlayer) {
this.videoPlayer = videoPlayer;
}
@Override
public void execute() {
videoPlayer.pause();
}
}
拖动进度条指令 SpeedCommand 类的代码如下。
public class SpeedCommand implements Command {
private VideoPlayer videoPlayer;
public SpeedCommand(VideoPlayer videoPlayer) {
this.VideoPlayer= videoPlayer;
}
@Override
public void execute() {
videoPlayer.speed();
}
}
停止播放指令 StopCommand 类的代码如下。
public class StopCommand implements Command {
private VideoPlayer videoPlayer;
public StopCommand(VideoPlayer videoPlayer) {
this.videoPlayer= videoPlayer;
}
@Override
public void execute() {
videoPlayer.stop();
}
}
最后创建控制条 Controller 类。
public class Controller {
private List<Command> Commands = new ArrayList<Command>();
public void addCommand(Command Command) {
Commands.add(Command);
}
public void execute(Command Command) {
Command.execute();
}
public void executes() {
for (Command Command : Commands) {
Command.execute();
}
Commands.clear();
}
}
从上面代码来看,控制条可以执行单条命令,也可以批量执行多条命令。下面来看客户端测试代码。
public class Test {
public static void main(String[] args) {
VideoPlayer player = new videoPlayer();
Controller controller = new Controller();
controller.execute(new PlayCommand(player));
controller.addCommand(new PauseCommand(player));
controller.addCommand(new PlayCommand(player));
controller.addCommand(new StopCommand(player));
controller.addCommand(new SpeedCommand(player));
controller.executes();
}
}
执行结果如下。
正常播放
暂停播放
正常播放
停止播放
拖动进度条
所有教程
- C语言入门
- C语言编译器
- C语言项目案例
- 数据结构
- C++
- STL
- C++11
- socket
- GCC
- GDB
- Makefile
- OpenCV
- Qt教程
- Unity 3D
- UE4
- 游戏引擎
- Python
- Python并发编程
- TensorFlow
- Django
- NumPy
- Linux
- Shell
- Java教程
- 设计模式
- Java Swing
- Servlet
- JSP教程
- Struts2
- Maven
- Spring
- Spring MVC
- Spring Boot
- Spring Cloud
- Hibernate
- Mybatis
- MySQL教程
- MySQL函数
- NoSQL
- Redis
- MongoDB
- HBase
- Go语言
- C#
- MATLAB
- JavaScript
- Bootstrap
- HTML
- CSS教程
- PHP
- 汇编语言
- TCP/IP
- vi命令
- Android教程
- 区块链
- Docker
- 大数据
- 云计算