Java设计模式:命令模式演示加法计算器
  TEZNKK3IfmPf 2023年11月14日 61 0
/**
 * 加法器,计算求和。
 * 
 * @author zhangfly
 *
 */
public class Adder {
	private int sum = 0;

	public int add(int value) {
		System.out.print("加法器计算:" + sum + "+(" + value + ")=");
		sum = sum + value;
		System.out.println(sum);
		return sum;
	}
}

 

public abstract class Command {
	public abstract int execute(int value);// 在原先和基础上再加上一个value的值。
	public abstract int undo(); // 撤销。
}

 


public class ConcreteCommand extends Command {
	private Adder adder = new Adder();
	private int value = 0;

	@Override
	public int execute(int value) {
		this.value = value;

		return adder.add(value);
	}

	@Override
	public int undo() {
		return adder.add(-value);
	}
}

 


public class Calculator {
	private Command command;

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

	// 执行运算.
	public void compute(int value) {
		int v = command.execute(value);
		System.out.println("运算结果:" + v);
	}

	// 调用命令对象的undo()方法执行撤销
	public void undo() {
		int v = command.undo();
		System.out.println("撤销,此时结果:" + v);
	}
}

 

public class Test {
	public Test() {
		Calculator calculator = new Calculator();
		Command command = new ConcreteCommand();
		calculator.setCommand(command);
		calculator.compute(1);
		calculator.compute(2);
		calculator.compute(3);
		calculator.compute(4);
		calculator.compute(5);
		calculator.undo();
	}

	public static void main(String[] args) {
		new Test();
	}
}

 

输出:

加法器计算:0+(1)=1
运算结果:1
加法器计算:1+(2)=3
运算结果:3
加法器计算:3+(3)=6
运算结果:6
加法器计算:6+(4)=10
运算结果:10
加法器计算:10+(5)=15
运算结果:15
加法器计算:15+(-5)=10
撤销,此时结果:10
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   20天前   46   0   0 java
  TEZNKK3IfmPf   2024年05月31日   54   0   0 java
TEZNKK3IfmPf