Behavioural Design patterns: Memento

The memento pattern is all about state. You use it when you want to restore the object to its previous state.
You have an object, you apply some actions and you are able to revert those actions and get the object in the various states it has been before.

Most of us implement various algorithms and sometimes we do need to evaluate em. Imagine having a program that evaluates trade decisions and you want to go to a previous state and check what would happen to the account balance if you change the formula, and then evaluate the account balance for each step.

The steps of the algorithm and what you should change will definitely vary. The memento pattern will assist us to our mission and help us do some fast in memory evaluation.

We will have a Memento object that contains the account balance.
Memento will represent the balance on different phases.

package com.gkatzioura.design.behavioural.memento;

public class Memento {

    private Double balance;

    public Memento(Double balance) {
        this.balance = balance;
    }

    public Double getBalance() {
        return balance;
    }
}

Then we will create the originator object. The originator will contain the current state. It can pass it back as a memento when we need to store it. Also we can use a memento object to it restore a certain state.

package com.gkatzioura.design.behavioural.memento;

public class Originator {

    private Double balance;

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    public Double getBalance() {
        return balance;
    }

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

    public void restoreToState(Memento memento) {
        balance =  memento.getBalance();
    }
}

The last step is the CareTaker object, this will contain the history of our balance. The caretaker will fetch the object state during their various phases.

package com.gkatzioura.design.behavioural.memento;

import java.util.ArrayList;
import java.util.List;

public class CareTaker {

    private List mementoList = new ArrayList();

    public void add(Memento state){
        mementoList.add(state);
    }

    public Memento get(int index){
        return mementoList.get(index);
    }

}

So let’s put them all together.

package com.gkatzioura.design.behavioural.memento;

public class MementoMain {

    public static void main(String[] args) {

        Double balance = 20.1d;

        Originator originator = new Originator();
        originator.setBalance(balance);

        CareTaker careTaker = new CareTaker();

        careTaker.add(originator.saveToMemento());

        /**
         * Do a transaction
         */

        originator.setBalance(balance-2);
        careTaker.add(originator.saveToMemento());

        /**
         * Do a transaction
         */

        originator.setBalance(balance+4);
        careTaker.add(originator.saveToMemento());

        System.out.println(careTaker.get(0).getBalance());
        System.out.println(careTaker.get(1).getBalance());
        System.out.println(careTaker.get(2).getBalance());
    }
}

You can find the source code on github.

Advertisement

Behavioural Design Patterns: Mediator

Previously we had a look at the iterator pattern.

The mediator pattern is way different on what it tries to achieve. It is one of the behavioural patterns and its purpose is to alter the way objects communicate with each other. Instead of the objects communicating with each other directly the mediator will handle the objects interaction.

For example imagine the scenario of a financial exchange. You do want to trade and buy but you don’t buy directly from the one that makes the offer.
Instead the exchange is in the middle, in order for you to make the transaction.

People would like to sell and buy. This shall be facilitated by the exchange.
You got the order object.

package com.gkatzioura.design.behavioural.mediator;

public class Order {

    private String stock;
    private Integer quantity;
    private Double price;

    public String getStock() {
        return stock;
    }

    public void setStock(String stock) {
        this.stock = stock;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

}

The next object would be the financial entity that sells the stocks.

package com.gkatzioura.design.behavioural.mediator;

public class FinancialEntity {

    public boolean sell(Order order) {

        /**
         * Supposing the sale was successful return true
         */
        return true;
    }

}

Then we create the exchange object. We won’t get further into commissions but imagine that things can be way more complex. The exchange is actually our mediator.

package com.gkatzioura.design.behavioural.mediator;

public class Exchange {

    private FinancialEntity financialEntity;

    public Exchange(FinancialEntity financialEntity) {
        this.financialEntity = financialEntity;
    }

    public void serve(Order order) {

        /**
         * Choose the financial entity suitable for the order
         */
        financialEntity.sell(order);
    }

}

And the last step is creating the trader object.

package com.gkatzioura.design.behavioural.mediator;

public class Trader {

    private Exchange exchange;

    public Trader(Exchange exchange) {
        this.exchange = exchange;
    }

    public void buy(String stock,Integer quantity,Double price) {
        Order order = new Order();
        order.setStock(stock);
        order.setQuantity(quantity);
        order.setPrice(price);
        exchange.serve(order);
    }

}

As you can see the trader object is not interacting directly with the financial entity that provides the stocks.

Let’s put them all together in a main class.

package com.gkatzioura.design.behavioural.mediator;

public class Mediator {

    public static void main(String[] args) {

        final FinancialEntity financialEntity = new FinancialEntity();
        final Exchange exchange = new Exchange(financialEntity);
        Trader trader = new Trader(exchange);
        trader.buy("stock_a",2,32.2d);
    }
}

That’s it, you just used the mediator pattern for an exchange application! You can also find the source code on github.

Fully working prototypes with Spring Boot and H2

We do use a lot of h2 with spring especially for unit tests. However instead of unit tests we might want to have a fully functional prototype with data to display.
H2 is the perfect candidate for that, it works great with spring, it has good syntax compatibility with most databases out there and it also provides you with a ui to check your data.

Imagine the scenario of an interview assignment. You want your example to work out of the box with as minimum as possible configuration for the reviewer.
The plan is to have an application up and running with some data.
Before accessing the application we might as well want to add some data to it. Then we need to have a proper way to display the data added without adding extra code.

The first step is to go to the spring initializr and add the Web and H2 dependencies. Also we shall add the jdbc property.

The end result will give a build.gradle file like this.

buildscript {
	ext {
		springBootVersion = '2.0.6.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.gkatzioura.springbooth2'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
	mavenCentral()
}

dependencies {
	implementation('org.springframework.boot:spring-boot-starter-jdbc')
	implementation('org.springframework.boot:spring-boot-starter-web')
	runtimeOnly('com.h2database:h2')
	testImplementation('org.springframework.boot:spring-boot-starter-test')
}

Since we added the jdbc property we can have some schema scripts executed once the application is started.
Thus we need to create a schema.sql file containing the sql statements which create the schema.

CREATE TABLE application_user (ID INT, USER_NAME VARCHAR(50), PASSWORD VARCHAR(255));
INSERT INTO application_user (ID,USER_NAME, PASSWORD) values (1,'test','password-hash');

The next step is to enable the h2 console. We will go with the yaml approach however you can do it either using a properties file or environment variables.

spring:
  h2:
    console:
      enabled: true

Now once we get our spring application running we can navigate at the http://localhost:8080/h2-console endpoint.
We shall be presented with the default credentials needed

Once we have logged in, we can query for the user we had inserted on our startup sql script.

Screen Shot 2018-11-05 at 07.36.20.png

That’s it! This can make wonders for prototypes, interview assignments and blog posts like this!