8 - 命令模式

文章目錄


參考:設計模式之禪

1. 例子

在這裏插入圖片描述

public interface Group {
    void find();
    void add();
    void delete();
    void change();
    void plan();
}
public class PageGroup implements Group {
    @Override
    public void find() {
        System.out.println("find page group");
    }
    @Override
    public void add() {
        System.out.println("add new page");
    }
    @Override
    public void delete() {
        System.out.println("delete page");
    }
    @Override
    public void change() {
        System.out.println("change page");
    }
    @Override
    public void plan() {
        System.out.println("do a page plan");
    }
}

.......
public abstract class Command {
    protected CodeGroup codeGroup = new CodeGroup();
    protected PageGroup pageGroup = new PageGroup();
    protected RequirementGroup requirementGroup = new RequirementGroup();
    public abstract void execute();
}
public class DeletePageCommand extends Command {

    @Override
    public void execute() {
        super.pageGroup.find();
        super.pageGroup.delete();
        super.pageGroup.plan();
    }
}
public class AddRequireCommandCommand extends Command {

    @Override
    public void execute() {
        super.requirementGroup.find();
        super.requirementGroup.delete();
        super.requirementGroup.plan();
    }
}
public class Invoker {
    private Command command;

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

    public void action() {
        command.execute();
    }
}

public class Client {
    public static void main(String[] args) {
        Invoker invoker = new Invoker();
        Command deletePageCommand = new DeletePageCommand();
        invoker.setCommand(deletePageCommand);
        invoker.action();
    }
}

2. 定義

把不同的請求封裝成不同的對象,使客戶端參數化。提供命令的撤銷和恢復功能。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章