302命令模式

98 阅读1分钟

定义

命令模式是一种设计模式,它可将请求转换为一个包含与请求相关的所有信息的独立对象。该转换让你能根据不同的请求将方法参数化,延迟请求执行或者将其放入队列中,且能实现撤销操作。

类图

图片1.png

图片2.png

代码

public class CommandPattern {
    public static void main(String[] args) {
        SaveButton saveButton = new SaveButton();
        TextBox box = new TextBox();
        PrintCommand printCommand = new PrintCommand(box);
        saveButton.bindCommand(printCommand);
        box.setContext("123");
        saveButton.doPrint();
        box.setContext("abc");
        saveButton.doPrint();
    }
}

//GUI层,保存数据
class SaveButton{
    private Command command;

    // 图像渲染  ---省略

    // 业务服务
    public void bindCommand(Command command){
        this.command=command;
    }

    public void doPrint(){
        if(command==null){
            throw new RuntimeException("设备初始化失败");
        }else{
            command.execute();
        }
    }
}

// 命令
interface Command{
    void execute();
}
class PrintCommand implements Command{
    private  PrintService serviceProvider = new PrintService();
    private TextBox box;
    public PrintCommand(TextBox box){
        this.box = box;
    }

    @Override
    public void execute() {
        serviceProvider.print(box.getContext());
    }
}
// 业务层,打印服务
class PrintService{
    public void print(String text){
        System.out.println(text);
    }
}
//文本区
class TextBox{
    private String context;
    public String getContext(){
        return context;
    }
    public void setContext(String context){
        this.context =context;
    }
}