[Design Pattern] Verhaltensmuster: Memento


#1
Hallo,

dieser Beitrag erklärt das Verhaltensmuster: Memento

Java:
package de.tutorials.design.patterns.behavioral;

import org.jpatterns.gof.MementoPattern.Caretaker;
import org.jpatterns.gof.MementoPattern.MementoImpl;
import org.jpatterns.gof.MementoPattern.Originator;

import de.tutorials.design.patterns.behavioral.MementoPatternExample.ObjectWithState.Memento;

public class MementoPatternExample {
	public static void main(String[] args) {
		ObjectWithState ows = new ObjectWithState(4711, 1.2345F, true);
		System.out.println(ows);
		
		new ObjectTester().test(ows);
		
		//Restored ObjectWithState
		System.out.println(ows);
	}
	
	@Caretaker
	static class ObjectTester{
		public void test(ObjectWithState ows){
			
			//Save current state to memento
			Memento memento = ows.saveToMemento(); 
			
			//manipulate the ows object
			ows.setValueA(123);
			ows.setValueB(999.222F);
			ows.setValueC(false);

			//manipulated ows 
			System.out.println(ows);
			
			ows.restoreFrom(memento);
		}
	}

	@Originator
	static class ObjectWithState {
		private int valueA;
		private float valueB;
		private boolean valueC;
		
		public ObjectWithState(){
		}

		public ObjectWithState(int valueA, float valueB, boolean valueC) {
			this.valueA = valueA;
			this.valueB = valueB;
			this.valueC = valueC;
		}

		public Memento saveToMemento() {
			return new Memento(this);
		}

		public void restoreFrom(Memento memento) {
			memento.restore(this);
		}

		@MementoImpl
		static class Memento {
			private final String state;

			public Memento(ObjectWithState ows) {
				this.state = ows.valueA + ";" + ows.valueB + ";" + ows.valueC;
			}

			public void restore(ObjectWithState objectWithState) {
				String[] elements = this.state.split(";");
				objectWithState.valueA = Integer.parseInt(elements[0]);
				objectWithState.valueB = Float.parseFloat(elements[1]);
				objectWithState.valueC = Boolean.valueOf(elements[2]);
			}

			public String getState() {
				return state;
			}
		}

		@Override
		public String toString() {
			return "ObjectWithState [valueA=" + valueA + ", valueB=" + valueB
					+ ", valueC=" + valueC + "]";
		}

		public int getValueA() {
			return valueA;
		}

		public void setValueA(int valueA) {
			this.valueA = valueA;
		}

		public float getValueB() {
			return valueB;
		}

		public void setValueB(float valueB) {
			this.valueB = valueB;
		}

		public boolean isValueC() {
			return valueC;
		}

		public void setValueC(boolean valueC) {
			this.valueC = valueC;
		}
	}
}
Ausgabe:
Code:
ObjectWithState [valueA=4711, valueB=1.2345, valueC=true]
ObjectWithState [valueA=123, valueB=999.222, valueC=false]
ObjectWithState [valueA=4711, valueB=1.2345, valueC=true]

Gruß Tom