11.26

命令模式

1
2
3
4
5
6
7
package src;
 
//抽象命令类   
public abstract class AbstractCommand {   
  public abstract int execute(int value); //声明命令执行方法execute()   
  public abstract int undo(); //声明撤销方法undo()   
}   

  

1
2
3
4
5
6
7
8
9
10
11
12
package src;
 
//加法类:请求接收者   
public class Adder {   
  private int num=0; //定义初始值为0   
       
  //加法操作,每次将传入的值与num作加法运算,再将结果返回   
  public int add(int value) {   
      num += value;   
      return num;   
  }   
}   

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package src;
 
public class CalculatorForm {   
    private AbstractCommand command;   
         
    public void setCommand(AbstractCommand command) {   
        this.command = command;   
    }   
         
    //调用命令对象的execute()方法执行运算   
    public void compute(int value) {   
        int i = command.execute(value);   
        System.out.println("执行结果为" + i);   
    }   
         
    //调用命令对象的undo()方法执行撤销   
    public void undo() {   
        int i = command.undo();   
        System.out.println("撤销:" + i);   
    }   

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package src;
 
public class Client {   
    public static void main(String args[]) {   
        CalculatorForm form = new CalculatorForm();   
        AbstractCommand command;   
        command = new ConcreteCommand();   
        form.setCommand(command); //向发送者注入命令对象   
             
        form.compute(3);   
        form.compute(4);   
        form.compute(5);   
        form.undo(); 
        form.undo();
        form.undo();
    }   
}   

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package src;
 
//具体命令类   
class ConcreteCommand extends AbstractCommand {   
  private Adder adder = new Adder();   
  private int value; 
  //实现抽象命令类中声明的execute()方法,调用加法类的加法操作   
  public int execute(int value) {   
          this.value=value;   
          return adder.add(value);   
      }   
           
      //实现抽象命令类中声明的undo()方法,通过加一个相反数来实现加法的逆向操作   
      public int undo() {   
          return adder.add(-value);   
      }   
  }   
posted @ 2021-11-26 22:31  韩佳龙  阅读(75)  评论(0编辑  收藏  举报