1

我正在阅读有关 Memento 设计模式的信息。我遇到了一个有关计算器撤消功能的示例。

我可以使用以下代码实现计算器撤消:

Calculator

public class Calculator implements Cloneable {

int num1;
int num2;
int result;

Stack<Calculator> states = new Stack<>();

public void setNum1(int num1) {
    this.num1 = num1;
}

public void setNum2(int num2) {
    this.num2 = num2;
}

public void setResult(int result) {
    this.result = result;
}

public int add() throws CloneNotSupportedException{
    result = num1 + num2;
    states.add((Calculator) this.clone());
    System.out.println("Caclulation done. ");
    return result;
}

public void undo(){
    states.pop();
    Calculator calc = states.peek();
    this.setNum1(calc.num1);
    this.setNum2(calc.num2);
    this.setResult(calc.result);
    System.out.println("Undo done. ");
}

public void displayState(){
    System.out.println("Current State: " + num1 + " + " + num2 + " = " + result);
}
}

CalculatorTest

    Calculator calc = new Calculator();

    calc.setNum1(10);
    calc.setNum2(11);
    calc.add();
    calc.displayState();

    calc.setNum1(12);
    calc.setNum2(13);
    calc.add();
    calc.displayState();

    calc.setNum1(16);
    calc.setNum2(17);
    calc.add();
    calc.displayState();

    calc.undo();
    calc.displayState();

    calc.undo();
    calc.displayState();

Output

Caclulation done. 
Current State: 10 + 11 = 21
Caclulation done. 
Current State: 12 + 13 = 25
Caclulation done. 
Current State: 16 + 17 = 33
Undo done. 
Current State: 12 + 13 = 25
Undo done. 
Current State: 10 + 11 = 21

它适用于撤消。为什么我要在这种情况下使用 Memento 模式?

4

1 回答 1

1

Source Memento Pattern

Motivation

It is sometimes necessary to capture the internal state of an object at some point and have the ability to restore the object to that state later in time. Such a case is useful in case of error or failure.

Consider the case of a calculator object with an undo operation such a calculator could simply maintain a list of all previous operation that it has performed and thus would be able to restore a previous calculation it has performed. This would cause the calculator object to become larger, more complex, and heavyweight, as the calculator object would have to provide additional undo functionality and should maintain a list of all previous operations.

This functionality can be moved out of the calculator class, so that an external (let's call it undo manager class) can collect the internal state of the calculator and save it. However providing the explicit access to every state variable of the calculator to the restore manager would be impractical and would violate the encapsulation principle.

于 2014-06-16T07:12:20.763 回答