在码农港湾
做一个实实在在的内行人

Java 命令模式

命令模式是数据驱动设计模式它是行为模式之一。

请求被作为命令的对象包装传递给invoker对象。

Invoker对象将命令传递到相应的对象并且该对象执行该命令。

例子

import java.util.ArrayList;
import java.util.List;

interface Command {
  void execute();
}

class MouseCursor {
  private int x = 10;
  private int y = 10;
  public void move() {
    System.out.println("Old Position:"+x +":"+y);
    x++;
    y++;
    System.out.println("New Position:"+x +":"+y);
    
  }

  public void reset() {
    System.out.println("reset");
    x = 10;
    y = 10;
  }
}

class MoveCursor implements Command {
  private MouseCursor abcStock;

  public MoveCursor(MouseCursor abcStock) {
    this.abcStock = abcStock;
  }

  public void execute() {
    abcStock.move();
  }
}

class ResetCursor implements Command {
  private MouseCursor abcStock;

  public ResetCursor(MouseCursor abcStock) {
    this.abcStock = abcStock;
  }

  public void execute() {
    abcStock.reset();
  }
}

class MouseCommands {
  private List<Command> orderList = new ArrayList<Command>();

  public void takeOrder(Command order) {
    orderList.add(order);
  }

  public void placeOrders() {
    for (Command order : orderList) {
      order.execute();
    }
    orderList.clear();
  }
}

public class Main {
  public static void main(String[] args) {
    MouseCursor cursor = new MouseCursor();

    MoveCursor moveCursor = new MoveCursor(cursor);
    ResetCursor resetCursor = new ResetCursor(cursor);

    MouseCommands commands= new MouseCommands();
    commands.takeOrder(moveCursor);
    commands.takeOrder(resetCursor);

    commands.placeOrders();
  }
}

上面的代码生成以下结果。


码农刷题必备工具 VS 码农进阶必读书籍

IT面试宝典宝典書城