Behavioural Design patterns: State

The state pattern deals with altering an object’s behaviour when its state changes.

Imagine the case of a class responsible for generating user interface based on the state. You got anonymous, logged-in and admin users.

We shall create an interface called GreetingState which defines the action of drawing a html text with a welcome message to the user. There is going to be a different implementation according to the states that we have.

package com.gkatzioura.design.behavioural.state;

public interface GreetingState {

    String create();

}

We shall implement the GreetingState for the anonymous user.

package com.gkatzioura.design.behavioural.state;

public class AnonymousGreetingState implements GreetingState {

    private static final String FOOTER_MESSAGE = "<p><Hello anonymous user!</p>";

    @Override
    public String create() {
        return FOOTER_MESSAGE;
    }

}

Then we shall implement the GreetingState for the logged in user. This one would create a personalised message.

package com.gkatzioura.design.behavioural.state;

public class LoggedInGreetingState implements GreetingState {

    private static final String FOOTER_MESSAGE = "<p><Hello %s!</p>";

    private final String username;

    public LoggedInGreetingState(final String username) {
        this.username = username;
    }

    @Override
    public String create() {
        return String.format(FOOTER_MESSAGE,username);
    }

}

And at last the admin Footer.

package com.gkatzioura.design.behavioural.state;

import java.util.Date;

public class AdminGreetingState implements GreetingState {

    private static final String FOOTER_MESSAGE = "<p><Hello %s, last login was at %s</p>";

    private final String username;
    private final Date lastLogin;

    public AdminGreetingState(final String username, Date lastLogin) {
        this.username = username;
        this.lastLogin = lastLogin;
    }


    @Override
    public String create() {
        return String.format(FOOTER_MESSAGE,username,lastLogin);
    }

}

The we shall create the stateui context.

package com.gkatzioura.design.behavioural.state;

import java.io.PrintWriter;

public class StateUIContext {

    private GreetingState greetingState;

    public void setGreetingState(GreetingState greetingState) {
        this.greetingState = greetingState;
    }

    public void create(PrintWriter printWriter) {
        printWriter.write(greetingState.create());
    }
}

Let’s put them all together.

package com.gkatzioura.design.behavioural.state;

import java.io.PrintWriter;
import java.util.Date;

public class StateMain {

    public static void main(String[] args) {

        StateUIContext stateUIContext = new StateUIContext();

        try(PrintWriter printWriter = new PrintWriter(System.out)) {
            stateUIContext.setGreetingState(new AnonymousGreetingState());
            stateUIContext.create(printWriter);
            printWriter.write("\n");
            stateUIContext.setGreetingState(new LoggedInGreetingState("someone"));
            stateUIContext.create(printWriter);
            printWriter.write("\n");
            stateUIContext.setGreetingState(new AdminGreetingState("admin",new Date()));
            stateUIContext.create(printWriter);
            printWriter.write("\n");
        }
    }
}

You can find the sourcecode on github.

Behavioural Design patterns: Observer

Observer is one of the most popular design patterns. It has been used a lot on many software use cases and thus many languages out there provide it as a part of their standard library.

By using the observer pattern we can tackle the following challenges.

  • Dependency with objects defined in a way that avoids tight coupling
  • Changes on an object changes its dependent objects
  • An object can notify all of its dependent objects

Imagine the scenario of a device with multiple sensors. Some parts of the code will need to get notified when new sensor data arrive and thus act accordingly. We will start by a simple class which represents the json data.

package com.gkatzioura.design.behavioural.observer;

public class SensorData {

    private final String sensor;
    private final Double measure;

    public SensorData(String sensor, Double measure) {
        this.sensor = sensor;
        this.measure = measure;
    }

    public String getSensor() {
        return sensor;
    }

    public Double getMeasure() {
        return measure;
    }
}

The we shall create the observer interface. Every class that implements the observer interface shall be notified once a new object is created.

package com.gkatzioura.design.behavioural.observer;

public interface Observer {

    void update(SensorData sensorData);

}

Next step is to create the observable interface. The observable interface will have methods in order to register the observers that need to get notified.

package com.gkatzioura.design.behavioural.observer;

public interface Observable {

    void register(Observer observer);

    void unregister(Observer observer);

    void updateObservers();

}

Now let us put some implementations.
The sensor listener will receive data from the sensors and notify the observers about the presence of data.

package com.gkatzioura.design.behavioural.observer;

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

public class SensorReceiver implements Observable {

    private List data = new ArrayList();
    private List observers = new ArrayList();

    @Override
    public void register(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void unregister(Observer observer) {
        observers.remove(observer);
    }

    public void addData(SensorData sensorData) {
        data.add(sensorData);
    }

    @Override
    public void updateObservers() {

        /**
         * The sensor receiver has retrieved some sensor data and thus it will notify the observer
         * on the data it accumulated.
         */

        Iterator iterator = data.iterator();

        while (iterator.hasNext()) {

            SensorData sensorData = iterator.next();

            for(Observer observer:observers) {
                observer.update(sensorData);
            }

            iterator.remove();
        }
    }

}

The we will create an observer which shall log the sensor data received to database, it might be an influxdb or an elastic search you name it.

package com.gkatzioura.design.behavioural.observer;

public class SensorLogger implements Observer {

    @Override
    public void update(SensorData sensorData) {

        /**
         * Persist data to the database
         */

        System.out.println(String.format("Received sensor data %s: %f",sensorData.getSensor(),sensorData.getMeasure()));
    }

}

Let’s put the all together.

package com.gkatzioura.design.behavioural.observer;

public class SensorMain {

    public static void main(String[] args) {

        SensorReceiver sensorReceiver = new SensorReceiver();
        SensorLogger sensorLogger = new SensorLogger();
        sensorReceiver.register(sensorLogger);
        sensorReceiver.addData(new SensorData("temperature",1.2d));
        sensorReceiver.updateObservers();
    }
}

You can find the source code on github.

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.

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.

Behavioural Design Patterns: Iterator

The iterator pattern is one of the most used patterns from the behavioural ones. Most of the times you use it without even noticing it. Supposing you have a container with elements and you want to traverse them. Iterating the elements might differ based on the container, retrieval method etc. By using the iterator pattern we can decouple the algorithms used by the containers, and the retrieval methods and abstract the iteration of the elements contained.

For example when it comes to retrieving paged data from a rest endpoint the iterator can help you to abstract it. Therefore you won’t expose the user with any information on how you retrieve the next batch of data.

I will make a new iterator interface similar the one provided by the java language.

package com.gkatzioura.design.behavioural.iterator;

public interface Iterator<T> {

    boolean hasNext();
    
    T next();
    
}

We will use the github jobs api since it is open to issue rest queries and search for jobs.
The first page is page zero.

https://jobs.github.com/positions.json?page=0.

We shall create a simple object which would contain the id, title and company information.

package com.gkatzioura.design.behavioural.iterator;

import java.util.UUID;

public class GitHubJob {

    private final UUID id;
    private final String company;
    private final String title;

    public GitHubJob(UUID id, String company, String title) {
        this.id = id;
        this.company = company;
        this.title = title;
    }

    public UUID getId() {
        return id;
    }

    public String getCompany() {
        return company;
    }

    public String getTitle() {
        return title;
    }
}

Our first step would be to create a repository witch shall fetch the data of the page specified.

package com.gkatzioura.design.behavioural.iterator;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class GitHubJobsRepository {

    public static final String GITHUB_JOB_API = "https://jobs.github.com/positions.json?page=";

    public List<GitHubJob> fetch(int page) throws Exception {

        List<GitHubJob> gitHubJobs = new ArrayList<>();

        URL url = new URL(GITHUB_JOB_API+page);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        String response = IOUtils.toString(httpConnection.getInputStream(), Charset.defaultCharset());
        JSONArray jsonArray = new JSONArray(response);

        for(int i=0;i<jsonArray.length();i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            GitHubJob gitHubJob = new GitHubJob(
                    UUID.fromString(jsonObject.getString("id")),
                    jsonObject.getString("company"),
                    jsonObject.getString("title"));
            gitHubJobs.add(gitHubJob);
        }

        return gitHubJobs;
    }

}

What’s great with this api is that if you ask for a page that does not exists you get an empty json object, thus asking for a non existing page won’t give us an exception like 404, therefore no need for error handling for this case.

Now the interesting part is the iterator.

package com.gkatzioura.design.behavioural.iterator;

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

public class GitHubIterator implements Iterator<GitHubJob> {

    private List<GitHubJob> currentJobsPage = new ArrayList<>();
    private int page = 0;

    private final GitHubJobsRepository gitHubJobsRepository;

    public GitHubIterator(GitHubJobsRepository gitHubJobsRepository) {
        this.gitHubJobsRepository = gitHubJobsRepository;
    }

    @Override
    public boolean hasNext() {
        fetchPageIfNeeded();
        return currentJobsPage.size()>0;
    }

    @Override
    public GitHubJob next() {
        fetchPageIfNeeded();

        if(currentJobsPage.size()==0) {
            return null;
        }

        return currentJobsPage.remove(0);
    }

    private void fetchPageIfNeeded() {
        if(page == -1) {
            return;
        }

        if(currentJobsPage==null||currentJobsPage.size()==0) {
            try {
                currentJobsPage = gitHubJobsRepository.fetch(page);
                if(currentJobsPage.size()==0) {
                    page = -1;
                } else {
                    page++;
                }
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}

The iterator shall contain a page request from github. For each element requested one item shall be removed from the page. Once the page gets empty a new page shall be requested.

Whether the user asks for another element or if another element exists the code shall check if the current page is empty and if yes it will request for the next page. If we got an empty page this mean that there should not be any extra request to the iterator.

The next step would be to add a method to the repository which shall give back the github iterator.

public class GitHubJobsRepository {

...

    public Iterator<GitHubJob> iterator() {
        return new GitHubIterator(this);
    }

...
}

So let us sum up and iterate over all the entries.

package com.gkatzioura.design.behavioural.iterator;

public class IteratorExample {

    public static void main(String[] args) throws Exception {
        GitHubJobsRepository gitHubJobsRepository = new GitHubJobsRepository();

        Iterator<GitHubJob> gitHubJobIterator = gitHubJobsRepository.iterator();

        while (gitHubJobIterator.hasNext()) {
            GitHubJob gitHubJob = gitHubJobIterator.next();
            System.out.println(String.format(" id: %s title: %s company: %s",gitHubJob.getId(),gitHubJob.getTitle(),gitHubJob.getCompany()));
        }
    }

}

You can find the source code on github.

It is also worth referencing patterns we saw previously such as the interpreter, chain of responsibility and the command pattern.

Behavioural Design Patterns: Interpreter

Previously we had a look at the chain of responsibility and the command pattern. They do tackle different problems however they both delegate an action to another component, the command patterns always delegates the action, the chain of responsibility if the action cannot be handled it will be forward it to its successor.

We are going to switch context and check the interpreter pattern.
The interpreter pattern specifies how to evaluate custom languages.
The examples are limitless, for example the spel language for spring or even a sql like language.

We will keep things simple and create an interpreter for a simple query language only with select and where statements. This is not impossible in the real world, just thing about dynamodb and how simple its expressions are, the examples are countless.

So let’s start with our clause interface.

package com.gkatzioura.design.behavioural.interpreter;

public interface Clause{

}

I will implement the WhereClause

package com.gkatzioura.design.behavioural.interpreter;


public class WhereClause implements Clause {

    /**
     * Add values related to the where clause functions and expressions
     */

    public WhereClause() {
    }

    /**
     * Add functions for expressions for equals not equals etc.
     */

}

And the SelectClause

package com.gkatzioura.design.behavioural.interpreter;

import java.util.Optional;

public class SelectClause implements Clause {

    private Optional<WhereClause> optWhereClause = Optional.empty();

    public <T> T load(Class<T> valueType) {

        /**
         * Apply filter according to the where clause
         */
        if(optWhereClause.isPresent()) {

        }

        /**
         * Load data
         */

        /**
         * Serialize/Deserialize data based on the type
         * For example if you use jackson it will be:  new ObjectMapper().readValue("text",valueType);
         */


        return null;
    }

    public void setWhereClause(WhereClause whereClause) {
        this.optWhereClause = Optional.of(whereClause);
    }
}

The load function shall load our data based on the expression given.

Both clauses are linked together however the select clause can produce results even when ‘where’ statements have not been given whatsoever. In any case when it comes to loading the data the select clause will check and apply any filter statements that the where clause might have (if exists) and then return the data.
Let’s move to the interpreter specific parts

We will create the expression interface.

package com.gkatzioura.design.behavioural.interpreter;

public interface Expression {

    Clause interpret(String context);

}

The interpretation of the text given will give us back a clause.

We shall create the WhereExpression.

package com.gkatzioura.design.behavioural.interpreter;

public class WhereExpression implements Expression {

    @Override
    public WhereClause interpret(String context) {
        WhereClause whereClause = new WhereClause();
        /**
         * Parse the string and find any where statements ie. A=1 AND B!=2 and apply them.
         */

        return whereClause;
    }

}

And the Select Expression.

package com.gkatzioura.design.behavioural.interpreter;

public class SelectExpression implements Expression {

    @Override
    public SelectClause interpret(String context) {
        SelectClause selectClause = new SelectClause();

        /**
         * Parse text and check for expressions like `SELECT * FROM ` or `SELECT A,B,C FROM` .
         */

        return selectClause;
    }

}

The last step would be the query expression.

package com.gkatzioura.design.behavioural.interpreter;

public class QueryExpression implements Expression {

    @Override
    public SelectClause interpret(String context) {

        SelectClause selectClause = new SelectExpression().interpret(context);

        if(context.contains("WHERE")) {

            WhereClause whereClause = new WhereExpression().interpret(context);
            selectClause.setWhereClause(whereClause);
        }

        return selectClause;
    }

}

So let’s put them all together. We shall interpret a query which fetches a list of integers.

package com.gkatzioura.design.behavioural.interpreter;

public class Interpreter {

    public static void main(String[] args) {
        String selectionString = "SELECT b FROM foo WHERE a=1";
        Integer[] values = new QueryExpression()
                .interpret(selectionString)
                .load(Integer[].class);
    }

}

You can find the sourcecode on github.

Behavioural Design Patterns: Command

Previously we used the Chain of Responsibility pattern in order to handle a complex problem with road incidents in a region, solving the problem in the first place or forwarding it to another incident handler.

The command pattern is quite different to the cor pattern since it helps us in order to delegate an action/request to another object capable of executing it. Thus there is no direct execution whatsoever.

For the command pattern we need an object to encapsulate all the information needed to perform an action or trigger an event sometime later.

One of the scenarios where it might seem very familiar is when it comes to queues and consuming those messages. Pretty much the same way elastic beanstalk workers consume messages from queues.

Each message in a queue contains a command and the code that handles that message has to execute it.
Let’s do this with an example from the betting industry.
We are going to have some bets being backed and sent over to our booking system.

So let’s create the bet class.

package com.gkatzioura.design.behavioural.command;

public class Bet {

    private final String match;
    private final Integer amount;

    public Bet(final String match, final Integer amount) {
        this.match = match;
        this.amount = amount;
    }

    public String getMatch() {
        return match;
    }

    public Integer getAmount() {
        return amount;
    }
}

Now let’s add a class which shall contain our bet actions. This is going to be our bet book.

package com.gkatzioura.design.behavioural.command;

public class BetBook {

    public void addBacking(String match, Integer amount) {
        /**
         * Add the backing to the book
         */
    }

}

Now it is time for us to specify the bet command. The bet command is going to be applied to our Bet book.

package com.gkatzioura.design.behavioural.command;

public interface BetCommand {

    void applyTo(BetBook betBook);

}

This brings us to the Backing command.

package com.gkatzioura.design.behavioural.command;

public class BackingCommand implements BetCommand {

    private final Bet bet;

    public BackingCommand(final Bet bet) {
        this.bet = bet;
    }

    @Override
    public void applyTo(BetBook betBook) {
        betBook.addBacking(bet.getMatch(),bet.getAmount());
    }

}

So let’s put them all together.

package com.gkatzioura.design.behavioural.command;

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

public class Command {

    public static void main(String[] args) {
        List<BetCommand> betCommands = new ArrayList<>();
        betCommands.add(new BackingCommand(new Bet("match1",10)));
        betCommands.add(new BackingCommand(new Bet("match2",11)));

        BetBook betBook = new BetBook();
        betCommands.forEach(bc->bc.applyTo(betBook));
    }

}

So imagine that we just gathered our bet commands and we got them dispatched to a microservice responsible to apply each command to our bet book.

You can find the source code on github.

Behavioural Design Patterns: Chain of Responsibility

We had a look on creational design patterns and structural design patterns. On this blog we will focus on behavioural design patterns.

From wikipedia

Behavioural design patterns are design patterns that identify common communication patterns between objects and realise these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Creational design patterns realise the creation of objects.
Structural design patterns provide ways to realise relationships with objects.
Behavioural design patterns realise the communication between objects.

The chain of responsibility pattern has to do with command objects being handled and passed to other objects by logic-containing processing objects.

There are many examples that come to mind. One of them is road infrastructure issues which need to be handled by towns, municipalities or states.

The towns should be responsible for its road issues, the municipality should handle the infrastructure that has to do with towns, hamlets and villages and the state all the rest such as urban roads, bridges etc.

There are various road incidents pothole, accidents, the collapse of a bridge you name it.
This brings us to the road incident model.

package com.gkatzioura.design.behavioural.cor;

public class RoadIncident {

    private final double latitude;
    private final double longtitude;
    private final String report;

    public RoadIncident(double latitude, double longtitude, String report) {
        this.latitude = latitude;
        this.longtitude = longtitude;
        this.report = report;
    }

    public double getLatitude() {
        return latitude;
    }

    public double getLongtitude() {
        return longtitude;
    }

    public String getReport() {
        return report;
    }
}

The latitude and longitude are the coordinates. Based on the coordinates each geographical region should proceed or pass the incident to the next region.

The next step is implementing the incident handler interface.

package com.gkatzioura.design.behavioural.cor;

public interface RoadIncidentHandler {

    void handle(RoadIncident roadIncident);

    boolean withinBounds(double lat, double lng);

}

Each geographical region should be identify if the incident is within its bound and should be handled by it. If not the incident should be forwarded to its successor.

We should start with the state road incident handler.

package com.gkatzioura.design.behavioural.cor;

public class StateRoadRoadIncidentHandler implements RoadIncidentHandler {

    @Override
    public void handle(RoadIncident roadIncident) {
        if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLatitude())) {
            throw new IllegalArgumentException("Incident cannot be handled by state. No successor available");
        }

        /**
         * Handle the incident
         */
    }

    @Override
    public boolean withinBounds(double lat, double lng) {

        /**
         * Reverse geolocation, look up by name, radius based distance etc.
         */

        return true;
    }
}

So the state has no successor. It is the highest level, thus if the incident is out of it’s bounds then it will throw an illegal argument exception.

Then we go to the municipality handler. The municipality handler does have a successor. It can be the state or something else we might come up in the future.

package com.gkatzioura.design.behavioural.cor;

public class MunicipalityRoadRoadIncidentHandler implements RoadIncidentHandler {

    private final RoadIncidentHandler successor;

    public MunicipalityRoadRoadIncidentHandler(final RoadIncidentHandler successor) {
        this.successor = successor;
    }

    @Override
    public void handle(RoadIncident roadIncident) {
        if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLongtitude())) {
            successor.handle(roadIncident);
        } else {
            /**
             * Handle the incident
             */
        }
    }

    @Override
    public boolean withinBounds(double lat, double lng) {
        /**
         * Reverse geolocation, look up by name, radius based distance etc.
         */
        return false;
    }
}

If the municipality incident handler is not able to handle the incident then it will forward it to its successor.

The last one is going to be the town road incident handler.

package com.gkatzioura.design.behavioural.cor;

public class TownRoadRoadIncidentHandler implements RoadIncidentHandler {

    private final RoadIncidentHandler successor;

    public TownRoadRoadIncidentHandler(final RoadIncidentHandler successor) {
        this.successor = successor;
    }

    @Override
    public void handle(RoadIncident roadIncident) {
        if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLongtitude())) {
            successor.handle(roadIncident);
        } else {
            /**
             * Handle the incident
             */
        }
    }

    @Override
    public boolean withinBounds(double lat, double lng) {
        /**
         * Reverse geolocation, look up by name, radius based distance etc.
         */
        return false;
    }
}

The same rule that applies to the municipality applies to the town handler. If the incident is not within its bounds it will forward it to its successor.

Let’s put them all together.

package com.gkatzioura.design.behavioural.cor;

public class ChainOfResponsibility {

    public static void main(String[] args) {
        StateRoadRoadIncidentHandler state = new StateRoadRoadIncidentHandler();
        MunicipalityRoadRoadIncidentHandler municipality = new MunicipalityRoadRoadIncidentHandler(state);
        TownRoadRoadIncidentHandler firstTown = new TownRoadRoadIncidentHandler(municipality);
        TownRoadRoadIncidentHandler secondTown = new TownRoadRoadIncidentHandler(state);

        RoadIncident roadIncident = new RoadIncident(0d,0d,"Something happened");
        firstTown.handle(roadIncident);
        secondTown.handle(roadIncident);
    }

}

So the municipality’s successor is the state. Also the state is the successor for the second town.
The first town has the municipality as the successor.

Regarding the first town if the incident can be handled only by the state then it will be forwarded from the first town to the municipality and then from the municipality to the state.
Regarding the second town if the incident cannot be handled it will be forwarded to the state.

You can find the sourcecode on github.

Structural Design Patterns: Proxy Pattern

Previously we used the facade pattern in order to interact with a legacy application. Our next pattern would be the proxy pattern.

The proxy pattern is used when we want

  • Control the access to an object
  • Add extra functionality when accessing an object.

One of the most common usages is when we want to monitor specific actions and add some metrics.

For example we have a data upload service.

package com.gkatzioura.design.structural.proxy;

public interface DataUploadService {

    void upload(String payload);

}

And its http implementation

package com.gkatzioura.design.structural.proxy;

public class HttpDataUploadImpl implements DataUploadService {

    @Override
    public void upload(String payload) {

    }

}

We need to have some measures on the average time it takes to send our application’s payload, in order to decide wether our implementation is good enough. If not we might need to consider something more performant.

Instead of messing with our implementation and adding code that has nothing to do with the actual transmission of the payload we shall create a proxy of our implementation.

package com.gkatzioura.design.structural.proxy;

import java.nio.charset.Charset;
import java.time.Duration;
import java.time.Instant;

public class HttpDataUploadProxy implements DataUploadService {

    private final HttpDataUploadImpl httpDataUpload;

    public HttpDataUploadProxy(HttpDataUploadImpl httpDataUpload) {
        this.httpDataUpload = httpDataUpload;
    }

    @Override
    public void upload(String payload) {

        Instant start = Instant.now();

        httpDataUpload.upload(payload);

        Duration duration = Duration.between(start,Instant.now());
        int byteSize = payload.getBytes(Charset.defaultCharset()).length;

        /**
         * Log properly to splunk, cloudwatch etc
         */
    }
}

As you can see our implementation hasn’t changed and we do manage to send the metrics needed to the analytics service of your choice.

We can also apply the same pattern in case this service has some quota and thus we want to control it because it might lead us to be over budget.

package com.gkatzioura.design.structural.proxy;

public class HttpDataUploadQuotaProxy implements DataUploadService {

    private final HttpDataUploadImpl httpDataUpload;

    public HttpDataUploadQuotaProxy(HttpDataUploadImpl httpDataUpload) {
        this.httpDataUpload = httpDataUpload;
    }

    @Override
    public void upload(String payload) {

        if(quotaExceeded()) {
            throw new IllegalStateException("Quota exceeded cannot upload payload");
        }

        httpDataUpload.upload(payload);
    }

    private boolean quotaExceeded() {

        /**
         * Code that should check whether we exceeded our quota or not
         */

        return false;
    }

}

Summing up we just used the proxy pattern in order to control the access to our object and also to enhance its functionality.

You can also find the source code on github.

Also I have compiled a cheat sheet containing a summary of the Structural Design Patterns.
Sign up in the link to receive it.

Structural Design Patterns: Facade Pattern

As developers most of the time we have to deal with complex systems, with many dependencies and even non existing documentation at all.

In these situations finding a way to tackle those challenges is essential. The most common way to deal with it, is to hide all those dependencies and specify a front facing interface.

The pattern to use in order to achieve is the facade pattern.

Somehow you end it up with a very complex system which generates reports in various ways. The system generates reports as xml files, csv files and even generates reports from a database.
The report generated in xml files extracts statistics based on a location, the report generated in csv files has to do with timeseries data and the database report about usage data.

The functionalities described above need to be incorporated to a web application.

The first step would be to create some interfaces based on each report.
The first interface will be the Geolocation report. By giving a location and a distance, a report shall be generated with locations within the distance specified from the point.

package com.gkatzioura.design.structural.facade;

import java.util.List;

public interface GeolocationReport {

     List<LocationInformation> generate(Double lat, Double lng, Double distance);

}

The Geolation report will be based on the xml reports generated from our system. Thus the implementation would be based on the xml report.

package com.gkatzioura.design.structural.facade;

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

public class XMLGeolocationReport implements GeolocationReport {

    @Override
    public List<LocationInformation> generate(Double lat, Double lng, Double distance) {

        /**
         * http requests to retrieve the xml
         * iterate the xml using stax
        */

        return new ArrayList<>();
    }

}

Our next report will have to do with time series data. Two dates will be given as an argument and thus the data needed will be retrieved.

package com.gkatzioura.design.structural.facade;

import java.util.Date;
import java.util.List;

public interface TimeSeriesReport {

    List<TimeInformation> generate(Date start, Date end);

}

Since the csv report is the one generated with time series data, our implementation will be based on the csv report of our system.

package com.gkatzioura.design.structural.facade;

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

public class CSVTimeSeriesReport implements TimeSeriesReport {

    @Override
    public List<TimeInformation> generate(Date start, Date end) {

        /**
         * retrieve the csv and iterate line by line with the time limits
         */

        return new ArrayList<>();
    }
}

The last step is the user usage report. A uuid representing the user shall be given.

package com.gkatzioura.design.structural.facade;

import java.util.List;
import java.util.UUID;

public interface UsageReport {

    List<Usage> report(UUID uuid);

}

The usage report will be based on the database report.

package com.gkatzioura.design.structural.facade;

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

public class SQLUsageReport implements UsageReport {

    @Override
    public List<Usage> report(UUID uuid) {

        return new ArrayList<>();
    }

}

So far we have abstracted the main functionalities of our system. Our next step is to create the facade which uses all those functionalities and bridges the gap between our web application needs and the the system that provides the information.
For example based on the user’s usage we need to have data based on the time and location of the user.

package com.gkatzioura.design.structural.facade;

import java.util.Date;
import java.util.List;
import java.util.UUID;

public interface UserUsageFacade {

    List<UserUsage> usageOn(UUID user, Date from, Double lat, Double lng);

}

And the implementation will use the report implementations in order to create the report that suits our web application.

package com.gkatzioura.design.structural.facade;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class UserUsageFacadeImpl implements UserUsageFacade {

    private final GeolocationReport geolocationReport;
    private final TimeSeriesReport timeSeriesReport;
    private final UsageReport usageReport;

    private final double DEFAULT_DISTANCE = 20d;
    private final int DEFAULT_TIME_RANGE = 20;

    public UserUsageFacadeImpl(GeolocationReport geolocationReport, TimeSeriesReport timeSeriesReport, UsageReport usageReport) {
        this.geolocationReport = geolocationReport;
        this.timeSeriesReport = timeSeriesReport;
        this.usageReport = usageReport;
    }

    @Override
    public List<UserUsage> usageOn(UUID user, Date from, Double lat, Double lng) {

        List locationInformationData = geolocationReport.generate(lat, lng, DEFAULT_DISTANCE);
        Date to = Date.from(from.toInstant().plusSeconds(DEFAULT_TIME_RANGE));
        List timeSetiesData = timeSeriesReport.generate(from, to);
        List usageData = usageReport.report(user);

        /**
         * Generate the report based on the data retrieved
         */

        return new ArrayList<>();
    }
}

You can find the source code on github.
Also you can find some helpful articles on the Adapter Pattern, the Decorator Pattern, the Composite Pattern and the Bridge Pattern.

Plus I have compiled a cheat sheet containing a summary of the Structural Design Patterns.
Sign up in the link to receive it.