命令模式是对命令的封装,每一个命令都是一个操作,请求方发出请求要求执行操作,接收方收到请求,并执行操作。命令模式解耦了请求方和接收方,请求方需要请求执行命令,不用关心命令怎么接口,怎样被操作,是否被执行等。属于行为型设计模式。
使用场景:
现在我们需要开发一个播放器,有播放功能,停止功能,拖动进度条功能。我们在操作播放器的时候并不是直接调用播放器的方法,而是通过一个控制条去传达指令给播放器内核,具体传达什么指令,被封装成一个一个按钮,每一个按钮就是对一条。命令的封装。
创建播放器内核核心类:
public class GPlayer {
public void play(){
System.out.println("播放功能");
}
public void stop(){
System.out.println("停止功能");
}
public void speed(){
System.out.println("拖动进度条");
}
}
创建命令接口:
public interface IAction {
void execute();
}
实现命令接口
public class PlayAction implements IAction{
private GPlayer gPlayer;
public PlayAction(GPlayer gPlayer) {
this.gPlayer = gPlayer;
}
@Override
public void execute() {
gPlayer.play();
}
}
public class SpeedAction implements IAction{
private GPlayer gPlayer;
public SpeedAction(GPlayer gPlayer) {
this.gPlayer = gPlayer;
}
@Override
public void execute() {
gPlayer.speed();
}
}
public class StopAction implements IAction{
private GPlayer gPlayer;
public StopAction(GPlayer gPlayer) {
this.gPlayer = gPlayer;
}
@Override
public void execute() {
gPlayer.stop();
}
}
创建控制条Controller
public class Controller {
public void execute(IAction action){
action.execute();
}
}
测试:
public class Test {
public static void main(String[] args) {
GPlayer gPlayer = new GPlayer();
Controller controller = new Controller();
controller.execute(new PlayAction(gPlayer));
controller.execute(new SpeedAction(gPlayer));
controller.execute(new StopAction(gPlayer));
}
}
uml类图:
原文:https://www.cnblogs.com/wwjj4811/p/14279407.html