Different ways to implement the Memento Pattern in Java - java

I am doing some research into the Memento Pattern and it seems that most of the examples I have come across seem to be relatively similar (Saving a String into an array and restoring it when needed) now correct me if I am wrong but I believe the method that i just described is "Object Cloning" but what are the other ways of implementing the Memento Pattern?
From what I have also picked up on Serialization can be used but there seems to be a grey area with people saying that it violates the encapsulation of the object and isn't a way to implement to Memento Pattern due to this.
So will anybody be able to shed some light on the ways to implement the pattern? My research has came up with a sort of mixture of all different things and has just made everything confusing.
Thanks

The Java Collections framework defines Queue, which can help.
Candidate code:
public final class Memento<T>
{
// List of saved values
private final Queue<T> queue = new ArrayDeque<T>();
// Last entered value, whether it has been saved or not
private T currentValue;
// No initial state, ie currentValue will be null on construction, hence
// no constructor
// Set a value, don't save it
public void set(final T value)
{
currentValue = value;
}
// Persist the currently saved value
public void persist()
{
queue.add(currentValue);
}
// Return the last saved value
public T lastSaved()
{
return queue.element();
}
// Return the last entered value
public T lastEntered()
{
return currentValue;
}
}
Notably missing from this code are many things, but are easily implementable:
revert to the last saved value;
no check for nulls;
T does not implement Serializable;
convenience method (like, add a value and make it the last saved state);
code is not thread safe!
Etc.
Sample code:
public static void main(final String... args)
{
final Memento<String> memento = new Memento<String>();
memento.set("state1");
System.out.println(memento.lastEntered()); // "state1"
memento.persist();
memento.set("state2");
System.out.println(memento.lastEntered()); // "state2"
System.out.println(memento.lastSaved()); // "state1"
}
In effect: this is a braindead implementation which can be improved, but which can be used as a basis -- extending it depends on your needs ;)

A usual problem that may come with memento implementations is that often there is a need for a lot of classes that represent the internal state of different kind of objects. Or the memento implementation must serialise object state to some other form (e.g. serialised java objects).
Here is a sketch for a memento implementation that doesn't rely on a specific memento class per class, whose state is to be captured for undo/redo support.
There's a basic concept to be introduced first:
public interface Reference<T> {
T get();
void set(T value);
}
This is an abstraction of java.lang.ref.Reference, because that class is for garbage collection purposes. But we need to use it for business logic. Basically a reference encapsulates a field. So they are intended to be used like that:
public class Person {
private final Reference<String> lastName;
private final Reference<Date> dateOfBirth;
// constructor ...
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public Date getDateOfBirt() {
return dateOfBirth.get();
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth.set(dateOfBirth);
}
}
Note that object instantiation with those references might not be that trivial, but we leave that out here.
Now here are the details for the memento implementation:
public interface Caretaker {
void addChange(Change change);
void undo();
void redo();
void checkpoint();
}
public interface Change {
Change createReversal();
void revert();
}
Basically a Change represents a single identifiable change to the state of an identifiable object. A Change is revertable by invoking the revert method and the reversal of that change can itself be reverted by reverting the Change created by the createReversal method. The Caretaker accumlates changes to object states via the addChange method. By invoking the undoand redo methods the the Caretaker reverts or redoes (i.e. reverting the reversal of changes) all changes until the next checkpoint is reached. A checkpoint represents a point at which all observed changes will accumulate to a change that transforms all states of all changed objects from one valid to another valid configuration. Checkpoints are usually created past or before actions. Those are created via the checkpoint method.
And now here is how to make use of the Caretaker with Reference:
public class ReferenceChange<T> implements Change {
private final Reference<T> reference;
private final T oldValue;
private final T currentReferenceValue;
public ReferenceChange(Reference<T> reference, T oldValue,
T currentReferenceValue) {
super();
this.reference = reference;
this.oldValue = oldValue;
this.currentReferenceValue = currentReferenceValue;
}
#Override
public void revert() {
reference.set(oldValue);
}
#Override
public Change createReversal() {
return new ReferenceChange<T>(reference, currentReferenceValue,
oldValue);
}
}
public class CaretakingReference<T> implements Reference<T> {
private final Reference<T> delegate;
private final Caretaker caretaker;
public CaretakingReference(Reference<T> delegate, Caretaker caretaker) {
super();
this.delegate = delegate;
this.caretaker = caretaker;
}
#Override
public T get() {
return delegate.get();
}
#Override
public void set(T value) {
T oldValue = delegate.get();
delegate.set(value);
caretaker.addChange(new ReferenceChange<T>(delegate, oldValue, value));
}
}
There exists a Change that represents how the value of a Reference has changed. This Change is created when the CaretakingReference is set. In this implementation there is a need for a nested Reference within the CaretakingReference implementation, because a revert of the ReferenceChange shouldn't trigger a new addChange via the CaretakingReference.
Collection properties needn't use the Reference. A custom implementation triggering the caretaking should be used in that case. Primitives can be used with autoboxing.
This implementation infers an additional runtime and memory cost by always using the reference instead of fields directly.

Related

Passing reference to instance into another object when new object is part of original object?

Could be there any flaw (from design perspective) when passing this instance of parent class into another object's constructor when new instance will be part of the original instance?
public class Order extends AbstractOrder {
private final OrderExecutionStrategy executionStrategy;
private Order() {
this.executionStrategy = new OrderExecutionStrategy(this);
}
// the implementation omitted for brevity...
}
I need to access data from parent instance in OrderExecutionStrategy class.
public class OrderExecutionStrategy extends AbstractOrderExecutionStrategy {
public OrderExecutionStrategy(final Order order) {
super(order);
}
#Override
public Optional<OrderPortion> executePortion(final BigDecimal newPrice, final TradeOrders orders) {
AssertUtils.notNull(orders, "orders");
AssertUtils.isGtZero(newPrice, "newPrice");
if (ComparisonUtils.equals(getOrder().getPrice(), newPrice)) {
final BigDecimal reaminingAmount = this.getOrder().summary().getRemainToFill();
if (ValidationUtils.isGtZero(reaminingAmount)) {
return Optional.of(new OrderPortion(this.getOrder().getId(), reaminingAmount));
}
}
return Optional.empty();
}
}
I can't see any design flaws in this.
However, there are a couple of caveats:
I am talking about design flaws, not implementation flaws.
"I am thinking that these two instances could negatively affect each other, an endless loop or something in that sense."
Those would be implementation flaws (aka bugs), not design flaws. A lot more context is required to check for that kind of thing.
You have only shown us a tiny part of the design, with few clues as to how this fits into the "bigger picture".

Java encapsulation concept not very clear

I have a bit of confusion with encapsulation concept. I have gone through quite a few answers on the same , but still confused. As far as I understand, encapsulation is to make instance variables as private so that outside cannot access this directly. Public getter and setter methods would be provided to access the private variables.
Suppose we have a class like below :
class Address
{
int doorNumber;
public int getDoorNumber()
{
//some code
}
public void setDoorNumber(int doorNumber)
{
//some code
}
}
We have another class from which we are trying to access the variable of Address class.
class TestAddress
{
public static void main()
{
Address add=new Address();
add.doorNumber=10; //cannot be done
add.setDoorNumber(10);
}
}
Though we are not accessing the variable directly , we are still modifying doorNumber using setter method to set the value of it to 10 . Basically the outside world can still access the private field and modify it in the way it wants. I do not understand what is the point of having encapsulation then . Can you please provide me some examples to understand encapsulation . Also scenarios where encapsulation was not used and problems which can occur because of that.
Look at the following counter-example:
class Address
{
int floor, door;
public int getDoorNumber()
{
return floor*100+door;
}
public void setDoorNumber(int doorNumber)
{
int newFloor=doorNumber/100;
if(newFloor<0 || newFloor>6)
throw new IllegalArgumentException("no such door "+doorNumber);
floor=newFloor;
door=doorNumber-newFloor*100;
}
}
The code calling setDoorNumber(10) still works without needing any change. The independence of the property “doorNumber” from the object’s internal representation, plus the possibility to validate the input value, are the key point of encapsulation. You can’t do that with a field like public int doorNumber;
Besides that, there are developers considering a method like setDoorNumber(int) being contradicting encapsulation, or at least, be a weak form of encapsulation. A stronger encapsulation model would work without such a public setter method but providing high-level operations only. Such an operation, like booking a room in a hotel would perform much more related operations, involving other objects, and consistency checks before internally assigning a room number to an address…
Using getters and setters has some benefits over making fields public :
You can redesign the internals of your class by replacing int doorNumber; with one or more fields of possibly different type. In such a case you can keep the getter and setter and that means other classes wouldn't have to be modified. If you had preferred private fields, any change in this class would enforce changes in any other class that uses it.
You can add validation and or reformatting logic inside a setter or getter, without changing the type of the field. Otherwise, if you used public fields, this logic would have to be repeated in any other class that accesses this field.
You can read more about it at Effective Java item 14
Consider this example:
public class Address {
private int doorNumber;
public int getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(int doorNumber) {
if (doorNumber <= 0) {
throw new IllegalArgumentException("door number must be > 0");
}
this.doorNumber = doorNumber;
}
}
If the doorNumber field was declared as public, some code could violate the constraint that the door numbers in addresses should be positive numbers.
Consider this example:
public class Address {
private String doorNumber;
public int getDoorNumber() {
return Integer.parseInt(doorNumber);
}
public String getDoorNumber2() {
return doorNumber;
}
public void setDoorNumber(int doorNumber) {
this.doorNumber = doorNumber + "";
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
}
Note that we evolving our API so that we can represent the address "221B Baker St, London", but still allowing our old "house numbers are integers" API to be used ... (sort of).
But if doorNumber had been public, then we would have been forced to change every place in the codebase where Address.doorNumber had been used.

Which contract is satisfied [duplicate]

If I have two interfaces , both quite different in their purposes , but with same method signature , how do I make a class implement both without being forced to write a single method that serves for the both the interfaces and writing some convoluted logic in the method implementation that checks for which type of object the call is being made and invoke proper code ?
In C# , this is overcome by what is called as explicit interface implementation. Is there any equivalent way in Java ?
No, there is no way to implement the same method in two different ways in one class in Java.
That can lead to many confusing situations, which is why Java has disallowed it.
interface ISomething {
void doSomething();
}
interface ISomething2 {
void doSomething();
}
class Impl implements ISomething, ISomething2 {
void doSomething() {} // There can only be one implementation of this method.
}
What you can do is compose a class out of two classes that each implement a different interface. Then that one class will have the behavior of both interfaces.
class CompositeClass {
ISomething class1;
ISomething2 class2;
void doSomething1(){class1.doSomething();}
void doSomething2(){class2.doSomething();}
}
There's no real way to solve this in Java. You could use inner classes as a workaround:
interface Alfa { void m(); }
interface Beta { void m(); }
class AlfaBeta implements Alfa {
private int value;
public void m() { ++value; } // Alfa.m()
public Beta asBeta() {
return new Beta(){
public void m() { --value; } // Beta.m()
};
}
}
Although it doesn't allow for casts from AlfaBeta to Beta, downcasts are generally evil, and if it can be expected that an Alfa instance often has a Beta aspect, too, and for some reason (usually optimization is the only valid reason) you want to be able to convert it to Beta, you could make a sub-interface of Alfa with Beta asBeta() in it.
If you are encountering this problem, it is most likely because you are using inheritance where you should be using delegation. If you need to provide two different, albeit similar, interfaces for the same underlying model of data, then you should use a view to cheaply provide access to the data using some other interface.
To give a concrete example for the latter case, suppose you want to implement both Collection and MyCollection (which does not inherit from Collection and has an incompatible interface). You could provide a Collection getCollectionView() and MyCollection getMyCollectionView() functions which provide a light-weight implementation of Collection and MyCollection, using the same underlying data.
For the former case... suppose you really want an array of integers and an array of strings. Instead of inheriting from both List<Integer> and List<String>, you should have one member of type List<Integer> and another member of type List<String>, and refer to those members, rather than try to inherit from both. Even if you only needed a list of integers, it is better to use composition/delegation over inheritance in this case.
The "classical" Java problem also affects my Android development...
The reason seems to be simple:
More frameworks/libraries you have to use, more easily things can be out of control...
In my case, I have a BootStrapperApp class inherited from android.app.Application,
whereas the same class should also implement a Platform interface of a MVVM framework in order to get integrated.
Method collision occurred on a getString() method, which is announced by both interfaces and should have differenet implementation in different contexts.
The workaround (ugly..IMO) is using an inner class to implement all Platform methods, just because of one minor method signature conflict...in some case, such borrowed method is even not used at all (but affected major design semantics).
I tend to agree C#-style explicit context/namespace indication is helpful.
The only solution that came in my mind is using referece objects to the one you want to implent muliple interfaceces.
eg: supposing you have 2 interfaces to implement
public interface Framework1Interface {
void method(Object o);
}
and
public interface Framework2Interface {
void method(Object o);
}
you can enclose them in to two Facador objects:
public class Facador1 implements Framework1Interface {
private final ObjectToUse reference;
public static Framework1Interface Create(ObjectToUse ref) {
return new Facador1(ref);
}
private Facador1(ObjectToUse refObject) {
this.reference = refObject;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Framework1Interface) {
return this == obj;
} else if (obj instanceof ObjectToUse) {
return reference == obj;
}
return super.equals(obj);
}
#Override
public void method(Object o) {
reference.methodForFrameWork1(o);
}
}
and
public class Facador2 implements Framework2Interface {
private final ObjectToUse reference;
public static Framework2Interface Create(ObjectToUse ref) {
return new Facador2(ref);
}
private Facador2(ObjectToUse refObject) {
this.reference = refObject;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Framework2Interface) {
return this == obj;
} else if (obj instanceof ObjectToUse) {
return reference == obj;
}
return super.equals(obj);
}
#Override
public void method(Object o) {
reference.methodForFrameWork2(o);
}
}
In the end the class you wanted should something like
public class ObjectToUse {
private Framework1Interface facFramework1Interface;
private Framework2Interface facFramework2Interface;
public ObjectToUse() {
}
public Framework1Interface getAsFramework1Interface() {
if (facFramework1Interface == null) {
facFramework1Interface = Facador1.Create(this);
}
return facFramework1Interface;
}
public Framework2Interface getAsFramework2Interface() {
if (facFramework2Interface == null) {
facFramework2Interface = Facador2.Create(this);
}
return facFramework2Interface;
}
public void methodForFrameWork1(Object o) {
}
public void methodForFrameWork2(Object o) {
}
}
you can now use the getAs* methods to "expose" your class
You can use an Adapter pattern in order to make these work. Create two adapter for each interface and use that. It should solve the problem.
All well and good when you have total control over all of the code in question and can implement this upfront.
Now imagine you have an existing public class used in many places with a method
public class MyClass{
private String name;
MyClass(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Now you need to pass it into the off the shelf WizzBangProcessor which requires classes to implement the WBPInterface... which also has a getName() method, but instead of your concrete implementation, this interface expects the method to return the name of a type of Wizz Bang Processing.
In C# it would be a trvial
public class MyClass : WBPInterface{
private String name;
String WBPInterface.getName(){
return "MyWizzBangProcessor";
}
MyClass(String name){
this.name = name;
}
public String getName(){
return name;
}
}
In Java Tough you are going to have to identify every point in the existing deployed code base where you need to convert from one interface to the other. Sure the WizzBangProcessor company should have used getWizzBangProcessName(), but they are developers too. In their context getName was fine. Actually, outside of Java, most other OO based languages support this. Java is rare in forcing all interfaces to be implemented with the same method NAME.
Most other languages have a compiler that is more than happy to take an instruction to say "this method in this class which matches the signature of this method in this implemented interface is it's implementation". After all the whole point of defining interfaces is to allow the definition to be abstracted from the implementation. (Don't even get me started on having default methods in Interfaces in Java, let alone default overriding.... because sure, every component designed for a road car should be able to get slammed into a flying car and just work - hey they are both cars... I'm sure the the default functionality of say your sat nav will not be affected with default pitch and roll inputs, because cars only yaw!

Best design pattern for a scenario

We have a class called Variable which represents a singlevalue or compound value. For example, it can hold an integer,or a boolean,or a String etc... (single valued) or some compound value which can be list of Strings, integers or other Variables.
We serialize these objects and in the stream all these values are represented as strings. Whenever we serialize or deserialize there is a type conversion happening.
There are also some optional features or ways you can fill values in these variables. For example you can define a Variable to be populated from a webpage - For a given Variable we query a cache to understand if it should be populated from a webpage. Whenever someone does getValue() on the Variable we populate the value.
We also want to track changes of some variables. For example, I can choose to record or do some action whenever the value of a variable is read or changed.
As you can see that this is a hierarchical structure because variable can contain other variables. We wanted to find the best way to solve this.
Currently we have only one class called Variable which has so many if/else conditions and the code is very complex.
For example, getValue() code does the following:
if(query the cache to see if it needs population from webpage)
do something
else(---)
do something
else(if read should be recorded-find from cache)
do something etc...
Is there any pattern to design my classes in such a way that all my population from webpage logic can go in to one class, tracking logic in some other class, type conversion logic in some other class etc... to make it more readable.
Chain of Responsibility Each chained element in the Composite gets to do it's bit, but you have to spend some time configuring the runtime structure just so.
Possibly just a Composite or Observer for the getValue() scenario (but sounds more like Composite to me).
EDIT:
One could argue that the implementation below is in fact a case of "Chain of Responsibility", as a composite variable will delegate the responsibility of setting values to its children.
END EDIT
Here's a simple example using Observer and Composite. NOT TESTED just to give you the general feel for the solution...
I have not implemented stuff like serializing/deserializing.
In this solution you have compound values and atomic values, and you can add some observer to be executed before value is set.
package dk.asj.variables;
public abstract class VariableBase {
public interface Observer {
void onSet(final Value val, final VariableBase var);
}
private Observer obs = null;
public void setObserver(final Observer obs) {
this.obs = obs;
}
public void setValue(final Value val) {
if (obs != null) {
obs.onSet(val, this);
}
internalSetValue(val);
}
protected abstract void internalSetValue(final Value val);
public abstract Value getValue();
}
package dk.asj.variables;
import java.util.List;
public interface Value {
int getIntValue();
String getStringValue();
List<Value> getCompositeValue();
}
package dk.asj.variables;
public class SimpleVariable extends VariableBase {
private Value val = null;
#Override
protected void internalSetValue(final Value val) {
this.val = val;
}
#Override
public Value getValue() {
return val;
}
}
package dk.asj.variables;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class CompoundVariable extends VariableBase {
final List<VariableBase> children = new LinkedList<VariableBase>();
public void addChild(final VariableBase c) {
children.add(c);
}
#Override
protected void internalSetValue(final Value val) {
for (int i = 0; i < val.getCompositeValue().size(); ++i) {
children.get(i).setValue(val.getCompositeValue().get(i));
}
}
#Override
public Value getValue() {
final List<Value> res = new ArrayList<Value>(children.size());
for (final VariableBase var : children) {
res.add(var.getValue());
}
return new Value() {
#Override
public int getIntValue() {
throw new RuntimeException("This is a composite value");
}
#Override
public String getStringValue() {
throw new RuntimeException("This is a composite value");
}
#Override
public List<Value> getCompositeValue() {
return res;
}
};
}
}
I'm not sure if this answers your question, however, this could lead to some new ideas, here is what I came up with in a similar situation:
I named these DynamicVariables. A dynamic variable may have a default value or be evaluated by a lamda (Java 8)/anonymous inner class (pre-Java 8).
Each variable has an evaluation context and can be evaluated only in a context - i.e. Session context or a Global context. Contexts fallback to each other and create an hierarchy, i.e. Session context falls back to a Global context. So the default variable constant or lambda value can be shadowed by a lambda or a constant defined in a context. In instance, session-scoped variables shadow out global vars when are accessed inside a session.
And this appeared to be quite a flexible approach - I even implemented a trivial dependency injection by introducing InjectionContext which is a thread-safe context holding an object being wired.
You might want to have a look at an example of how this is used in a deployment tool I'm currently developing. Configuration management and shared application logic there is built upon these variables. Code is under bear.context package, but it's rather raw at the moment.

Extending class in Java and constructing using an instance of the extended class

I would like to extend a class and then copy the value from an instance of the class which has been extended, so I get all its parameters in my new class. In case this doesn't make sense, a simple example of what I'm trying to do:
public class MyTableModel extends DefaultTableModel {
public MyTableModel(DefaultTableModel model){
this = (MyTableModel) model; /* I realise this is invalid */
}
public newMethod(){
// Some additional code
}
}
Is this possible to achieve?
It looks like you want composition instead of inheritance. In particular, it looks like you're trying to use the decorator pattern. That is, you want to take an existing instance of DefaultTableModel, and create another DefaultTableModel that forwards most of the methods to the underlying delegate, but perhaps adding/modifying/decorating some functionalities.
You can never set this = somethingElse;, but you can have a DefaultTableModel delegate, and forward most/all requests to delegate, perhaps adding/decorating some methods as necessary.
See also
Effective Java 2nd Edition, Item 16: Favor composition over inheritance
Guava Example: ForwardingCollection
An example of this pattern is ForwardingCollection from Guava:
A java.util.Collection which forwards all its method calls to another collection. Subclasses should override one or more methods to modify the behavior of the backing collection as desired per the decorator pattern.
You can see the source code to see how this pattern is typically implemented:
#Override protected abstract Collection<E> delegate();
public int size() {
return delegate().size();
}
public boolean isEmpty() {
return delegate().isEmpty();
}
public boolean removeAll(Collection<?> collection) {
return delegate().removeAll(collection);
}
// many more interface Collection methods implemented like above...
As you can see, all the ForwardingCollection does is it implements Collection simply by forwarding all methods to its delegate(), another Collection. Understandably this is rather repetitive and mundane code to write, but now subclasses can simply extends ForwardingCollection and only decorate what they want to decorate.
You can't not set this in Java to anything, it is just used for expressions like (this == someObject) or accessing some property of the object being currently used like (this.someProperty) or inside a constructor to initialize the current object. See here for more info about the this keyword
This code will likely throw a java.lang.ClassCastException
That is MyTableModel is a DefaultTableModel but DefaultTableModel is not a MyTableModel. See http://java.sun.com/docs/books/jls/third_edition/html/conversions.html for more details about type conversion in java
If there is some state and/or behavior that you want to reuse from your parent class in your subclass you should consider marking those members as protected, or consider other form of composition.
A better way to do this would be to make the fields of the superclass protected instead of private - this will give you access to them in your subclass.
Note that when you defined the subclass constructor, you will need to call a constructor from the superclass as well, so in that respect you'll still be able to pass in all the required variables.
And don't forget that all public methods in the superclass can be called as-is by any code that has an instance of your subclass.
EDIT: A little example might help:
public class DefaultTableModel
{
protected String modelName;
protected int numberOfTables;
private numTimesReinited = 0;
public DefaultTableModel(String name, int numTabs)
{
modelName = name;
numberOfTables = numTabs;
}
public void reinit()
{
numTimesReinited++;
// Other stuff
}
protected int getNumberOfReinits()
{
return numTimesReinited;
}
public String getName()
{
return name;
}
}
public class MyTableModel extends DefaultTableModel
{
private String modelType;
public MyTableModel(String name, int numTables, String modelType)
{
super(name, numTables); // sets up the fields in the superclass
this.modelType = modelType;
}
// purely "local" code
public void getModelType()
{
return modelType;
}
// Accesses several protected data to provide new (public) functionality
public void addTable()
{
if (getNumberOfReinits() < 10)
{
numberOfTables++;
reinit();
}
}
}
Let me know if I've misunderstood your requirements, but it sounds like you want to access fields and behaviour of the superclass - which you'll have automatic access to in your subclass so long as they're not private.

Categories