栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

一起走进命令模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

一起走进命令模式

目录
        • 一.介绍
        • 二.场景约束
        • 三.UML类图
        • 四.示意代码
        • 五.优点
        • 六.在JDK中的应用

一.介绍

命令模式(Command Pattern)属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令,执行顺序是调用者→命令→接收者,实现调用者(Invoker)与接收者(Receiver)解耦

二.场景约束

设计一个文本编辑器(TextField),支持复制、插入以及撤销操作

三.UML类图

四.示意代码

业务代码

//抽象命令
public interface Command {
    void execute();

    void undo();
}

//调用者
class Invoker{
    private Command command;

    public Invoker(Command command) {
        this.command = command;
    }

    public void setCommand(Command command) {
        this.command = command;
    }

    public void call(){
        command.execute();
        command.undo();
    }
}

//具体命令
class insertCommand implements Command {
    private TextField textField;

    private String insertStr = "insertStr";

    public insertCommand(TextField textField) {
        this.textField = textField;
    }

    @Override
    public void execute() {
        textField.text += insertStr;
        System.out.println(textField.text);
    }

    @Override
    public void undo() {
        textField.text = textField.text.substring(0, textField.text.length() - insertStr.length());
        System.out.println(textField.text);
    }
}

//具体命令
class CopyCommand implements Command {
    private TextField textField;

    public CopyCommand(TextField textField) {
        this.textField = textField;
    }

    @Override
    public void execute() {
        textField.text += textField.text;
        System.out.println(textField.text);
    }

    @Override
    public void undo() {
        textField.text = textField.text.substring(0, textField.text.length() / 2);
        System.out.println(textField.text);
    }
}

//接收者
class TextField {
    public String text = "text";
}

客户端

public class Client {
    public static void main(String[] args) {
        Invoker invoker = new Invoker(new CopyCommand(new TextField()));
        invoker.call();
    }
}
五.优点
  • 优点
    • 新增、删除命令非常方便
    • 符合开闭原则
    • 命令可以组合,同时支持命令的撤销和恢复
    • 命令可以增加统一功能:日志、权限
    • 调用者与接收者解耦
六.在JDK中的应用

java.lang.Runnable是一个典型的命令模式,Runnable充当抽象命令的角色,Thread充当调用者的角色,而接收者的角色是开发者自己定义的

//具体命令
class ConcreteCommand implements Runnable{
    private Receiver receiver;

    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void run() {
        receiver.execute();
    }
}

//接收者
class Receiver{
    public void execute(){
        System.out.println("执行逻辑");
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683339.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号