記念品がどのように実装されることになっているかについて、私は非常に混乱しています。
MementoにはStateがあることを理解しています。また、Memento パターンは、オブジェクトを以前の状態に復元できるように、さまざまな (以前の)状態を保存するために使用されます。
複数のオブジェクトがあるとしましょう。それぞれに 10 個の属性があり、そのうちの 5 個は個々のオブジェクトの存続期間を通じて同じままですが、そのうちの 5 個は変更されます。したがって、各オブジェクトが以前の状態を保存してそれらに戻る必要があります。
質問:
これらのオブジェクトにMemento パターンを適用するにはどうすればよいですか?
これまでの私の考え:
したがって、 Memento パターンには 3 つのクラスがあり、Mementoには、状態ごとに 1 つずつ、多数のクラスを作成します。オブジェクト AKA Mementosの以前の状態をすべて保存する世話人。次に、Mementosを作成し、 Mementoから状態を取得するOriginatorです。
これは、各オブジェクト インスタンスが独自のCaretaker インスタンス(以前の状態のリスト) を必要とすることを意味し、このCaretakerは、このオブジェクトの 5 つの属性の以前の状態 (および現在の状態または以前のもののみ?)を持つMementosを持つことになります。ただし、世話人を持つすべてのオブジェクトは、同じOriginator インスタンスを使用できます。これは、Originatorを使用して、任意のCaretakerに新しい記念品を作成できるためです。
これは実装方法ですか、それとも誤解していますか?
次のようになります。
オリジネーターとメメントクラス
public class Memento {
private Object1Attributes state;
public Memento(Object1Attributes state){
this.state = state;
}
public Object1Attributes getState(){
return state;
}
}
static class Originator {
private Object1Attributes state;
public Memento saveStateToMemento(){
return new Memento(state);
}
public void getStateFromMemento(Memento Memento){
state = Memento.getState();
}
public void setState(Object1Attributes state){
this.state = state;
}
public Object1Attributes getState(){
return state;
}
}
その他のオブジェクト
public class Object1Attributes{
string attribute1;
int attribute2;
someObject attribute3;
someObject attribute4;
someObject attribute5;
}
public class Object1 {
CareTaker careTaker = new CareTaker();
Object1Attributes;
string attribute6;
int attribute7;
someObject attribute8;
someObject attribute9;
someObject attribute10;
public void returnToPreviousState(){
if(caretaker.Length()>0){
Object1Attributes = originator.getStateFromMemento(careTaker.get(caretaker.Length()-1));
caretaker.remove(caretaker.Length()-1);
}
}
public void newState(ObjectAttributes OA){
originator.setState(OA);
this.ObjectAttributes = OA;
this.caretaker.add(originator.saveStateToMemento());
}
}
別のオプション
別のクラス内に 5 つの属性をカプセル化するのではなく、Memento クラスと Originator クラスが 5 つの属性を保持するようにします。そのようです:
public class Originator {
string attribute1;
int attribute2;
someObject attribute3;
someObject attribute4;
someObject attribute5;
public Memento saveStateToMemento(){
return new Memento(attribute1, attribute2, attribute3, attribute4, attribute5);
}
public void setAttribute1(string state){
this.attribute1 = state;
}
public void setAttribute2(int state){
this.attribute2 = state;
}
}
この方法では、各 Object1 インスタンスは Object1Attributes ではなく Originator の独自のインスタンスを保持し、この Originator には object1 インスタンスの属性の現在の状態が含まれます。パターンを実装する正しい方法がどれかわかりません。
オンラインのすべての例では、単なる文字列である「状態」を保存するために mementos を使用していますが、複数の状態を持つことができる複数のオブジェクトの作成を伴うものはないため、よくわかりません。