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.

Structural Design Patterns: Decorator Pattern

Previously we altered the behaviour of our abstract objects using the bridge pattern and we implemented a tree like structure for our components using the composite pattern and delegating the requests.

The decorator pattern allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

So imagine the scenario of applying various discounts to one of our products.

We will start with the discount interface to specify the discount action.

package com.gkatzioura.design.structural.decorator;

import java.math.BigDecimal;

public interface Discount {
    
    BigDecimal apply(BigDecimal originalPrice);
    
}

An object which shall implement the discount will apply the discount and give back the discounted price.
One of the discounts that we want to apply is a special discount for newly registered members.
Newly registered members will have 20% off on their first order

package com.gkatzioura.design.structural.decorator;

import java.math.BigDecimal;

public class NewlyRegisteredDiscount implements Discount {

    public static final BigDecimal SEVENTY_FIVE = new BigDecimal(75);
    public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);

    @Override
    public BigDecimal apply(BigDecimal originalPrice) {

        return originalPrice.multiply(SEVENTY_FIVE).divide(ONE_HUNDRED);
    }

}

As you have experienced sometimes more than one discounts are applied.
Our system also provides our customers with coupon discounts of 5 dollars off.

It is very comon to apply multiple discounts and our systems has to support this action. It is common to create discount packages which in reality are just a compination of packages.
To do so we will utilize the decorator pattern.
We will create the discount decorator.

package com.gkatzioura.design.structural.decorator;

import java.math.BigDecimal;

public class DiscountDecorator implements Discount {

    protected Discount discount;

    public DiscountDecorator(Discount discount) {
        this.discount = discount;
    }

    @Override
    public BigDecimal apply(BigDecimal originalPrice) {
        return discount.apply(originalPrice);
    }
}

So we want to have a first purchase discount and a 5 dollars of discount for new users referenced by other users.
We will call this discount as ‘referenced user’ discount.
The goal is to have 5 dollars off and a discount applied to the original price.

package com.gkatzioura.design.structural.decorator;

import java.math.BigDecimal;

public class ReferencedUserDiscount extends DiscountDecorator {

    public static final BigDecimal FIVE = new BigDecimal(5);

    public ReferencedUserDiscount(Discount discount) {
        super(discount);
    }
    
    @Override
    public BigDecimal apply(BigDecimal originalPrice) {

        BigDecimal discountedPrice = super.apply(originalPrice);

        if(discountedPrice.compareTo(FIVE)<=0) {
            return discountedPrice;
        }

        return discountedPrice.subtract(FIVE);
    }
}

Imagine now the scenario of a loyalty discount. We want a two year plan for our users with a discount of 5% for each one of their orders.

package com.gkatzioura.design.structural.decorator;

import java.math.BigDecimal;

public class TwoYearPlanDiscount extends DiscountDecorator {

    public static final BigDecimal NINETY_NINE = new BigDecimal(95);
    public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);

    public TwoYearPlanDiscount(Discount discount) {
        super(discount);
    }

    @Override
    public BigDecimal apply(BigDecimal originalPrice) {
        return super.apply(originalPrice).multiply(NINETY_NINE).divide(ONE_HUNDRED);
    }

}

As you can see both in the cases of the referenced user discount and both in the case of the two years plan discount we didn’t alter our original discount for our newly registered users. What we did is decorating the original discount and giving back the discount by taking into account the various options.

The decorator pattern is about

  • Add Responsibilities or remove them from an object dynamically at run-time.
  • Extend functionality in a flexible way without subclassing

So let’s put our plan into action.

package com.gkatzioura.design.structural.decorator;

import java.math.BigDecimal;

public class DecoratorScenario {

    public static void main(String args[]) {

        NewlyRegisteredDiscount newlyRegisteredDiscount = new NewlyRegisteredDiscount();
        ReferencedUserDiscount referencedUserDiscount = new ReferencedUserDiscount(newlyRegisteredDiscount);
        TwoYearPlanDiscount twoYearPlanDiscount = new TwoYearPlanDiscount(referencedUserDiscount);
        BigDecimal discountPrice = twoYearPlanDiscount.apply(new BigDecimal(100));
    }

}

Our newly registered users will have three types of discounts.

You can find the sourcecode 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: Composite Pattern

Previously we checked the adapter pattern the use cases and the bridge pattern. The pattern we will examine in this post is the composite pattern.
By following the composite pattern we “compose” objects into tree structures representing part-whole hierarchies, therefore clients can treat individual objects and compositions uniformly.

By referencing the word hierarchies the first thing that comes to mind is organisations. A military organisation is a great example for the composite pattern.

One of the most basic actions of military personnel is to execute orders.
Thus we will make an interface which specifies the ability to execute orders.

package com.gkatzioura.design.structural.composite;

public interface MilitaryPersonnel {

    void executeOrder();

}

The private is the lowest rank in a military organisation. A private cannot delegate a task or give orders. Therefore he will just execute an order.

package com.gkatzioura.design.structural.composite;

public class Private implements MilitaryPersonnel {

    @Override
    public void executeOrder() {

    }

}

Above the private there are other ranks like Major, Lieutenant, Colonel etc. Those are officer ranks and officers execute orders but also they can assign orders.
So the Officer interface will specify the ability to assign orders.

package com.gkatzioura.design.structural.composite;

public interface Officer {

    void assignOrder();

}

Be aware that an officer in order to execute an order he will take some actions on his own and he might as well assign some orders to lower rank personnel.

So the Lieutenant will be able to execute orders but also to assign orders to ranks lower that him.

package com.gkatzioura.design.structural.composite;

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

public class Lieutenant implements MilitaryPersonnel, Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public Lieutenant(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    public void addPrivateUnderCommand(Private soldier) {
        lowerRankersonel.add(soldier);
    }
    
    @Override
    public void executeOrder() {
        
        //other actions

        assignOrder();

        //other actions.
    }

    @Override
    public void assignOrder() {

        lowerRankersonel.forEach(lr->lr.executeOrder());
    }
}

The same that applies to the lieutenant applies to the major who is able to execute orders and assign orders to lower ranks.

package com.gkatzioura.design.structural.composite;

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

public class Colonel implements MilitaryPersonnel, Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public Colonel(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    public void addPrivateUnderCommand(Private soldier) {
        lowerRankersonel.add(soldier);
    }

    public void addLieutenantUnderCommand(Lieutenant lieutenant) {
        lowerRankersonel.add(lieutenant);
    }

    @Override
    public void executeOrder() {
        //other actions

        assignOrder();

        //other actions
    }

    @Override
    public void assignOrder() {
        lowerRankersonel.forEach(lr->lr.executeOrder());
    }
}

In our scenario the general is the highest rank and thus when he assigns an order this order will be executed by the composite we implemented.

package com.gkatzioura.design.structural.composite;

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

public class General implements  Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public General(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    @Override
    public void assignOrder(MilitaryPersonnel militaryPersonnel) {
        militaryPersonnel.executeOrder();
    }
}

And a main class will display the composite’s functionality.

package com.gkatzioura.design.structural.composite;

import java.util.Collections;

public class CompositeScenario {

    public static void main(String[] args) {

        Private ryan = new Private();
        Lieutenant lieutenant = new Lieutenant(Collections.singletonList(ryan));
        Major major = new Major(Collections.singletonList(lieutenant));
        General general = new General();
        general.assignOrder(major);
    }
}

As you can see the general object, which is the client treated all the objects uniformly.
The whole hierarchy is represented in a tree structure.
The private is the leaf the major and the lieutenant represent the Composite that forwards the requests to the corresponding child components.

You can 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: Bridge Pattern

On the previous post we had a look at the adapter pattern. On this blog we are going to use the bridge pattern.
As mentioned by GOF the bridge pattern usage is to “decouple an abstraction from its implementation so that the two can vary independently”.
How this translates to a software problem?
Imagine that you need to implement software for missiles.

You have Ballistic missiles, Cruise missiles, Rockets etc. Although they are all missiles and they may explode, their mechanisms differ a lot from type to type.

Taking the above into consideration most probably you are going to end with many layers of abstractions.
The missile and what it does vary a lot. And this is what the bridge pattern is all about. There is going to be a rocket abstraction and it’s behaviour will become largely different by providing a different component implementation, in our case the igniter.

We have one rocket interface specifying the missile actions.

package com.gkatzioura.design.structural.bridge;

public interface Missile {

    void explode();

}

And another interface which specifies the igniter actions.

package com.gkatzioura.design.structural.bridge;

public interface Igniter {

    void ignite();
}

And we are going to have a pyrogenic igniter implementation

package com.gkatzioura.design.structural.bridge;

public class PyrogenIgniter implements Igniter {

    public void ignite() {

    }
}

Last but not least we are going to have an AirToAirMissile implementation.

package com.gkatzioura.design.structural.bridge;

public class AirToAirMissile implements Missile {

    private Igniter igniter;

    public AirToAirMissile(Igniter igniter) {
        this.igniter = igniter;
    }

    public void explode() {

        //Actions relation to explosion

        igniter.ignite();
    }
}

So we will implement an air to air missile.

AirToAirMissile airToAirMissile = new AirToAirMissile(new PyrogenIgniter());

As you can understand missile components vary and based on the components their functionality changes.

You can 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: Adapter Pattern

On previous blog posts we focused on creational design patterns such as the builder pattern, the abstract factory/factory pattern, the singleton and the prototype pattern.

We will switch our focus to the structural design patterns. By using structural design patterns our goal is to ease the design by identifying a simple way to realize relationships between entities.

Adapter pattern is one of the most used and well known structural patterns.
Its major usage is when you want to make classes work with other classes without having to change its source code.

Imagine the scenario of refactoring some code and you stumble upon a class sending emails.

package com.gkatzioura.design.structural.adapter;

import java.util.List;

public class MailSender {

    private String title;
    private String message;
    private List<String> recipients;

    public MailSender(String title, String message, List<String> recipients) {
        this.title = title;
        this.message = message;
        this.recipients = recipients;
    }

    public void sendMessage() {

    }

    public void sendHtmlMessage(String htmlTemplate) {

    }

}

The MailSender class has the ability to send an email but also you can use it in order to send an email containing html.

We want to add some subscribe/notify functionality in our code base so that people could receive a simple message in the form of sms, email, webhooks etc.

We have also come up with an interface for the notify functionality.

package com.gkatzioura.design.structural.adapter;

public interface Notifier {

    void notify(String recipients,String message);

}

As you can see our notify action does not really care about the subject or formatting of the message. You just have to notify the subscribes.
Among the rest implementation an email implementation should be provided.
We can either provide a new email implementation which implements the notifier interface or we can change the original email class.

However there is a third option. You can use the adapter pattern and create a class so that you can reuse your old email class.

By doing this you don’t alter your old email class and therefore the code which uses its functionality and also you skip creating a new class therefore having to maintain one extra class.

package com.gkatzioura.design.structural.adapter;

import java.util.List;

public class MailNotifierAdapter implements Notifier {

    private static final String NOTIFICATION_TITLE = "System notification";
    
    public void notify(List<String> recipients, String message) {
        
        MailSender mailSender = new MailSender(NOTIFICATION_TITLE,message,recipients);
        mailSender.sendMessage();
    }
}

You can find the sourcecode 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.

Creational Design Patterns: Prototype Pattern

The prototype pattern is used in order to create a copy of an object. This pattern can be really useful especially when creating an object from scratch is costly.
In comparison with the builder, factory and abstract factory patterns it does not create an object from scratch it clones/recreates it.
In comparison with the singleton pattern it creates multiple copies of an instance whilst the singleton has to ensure that only one will exist.

Imagine the scenario of an object, which in order to be created requires a very resource intensive method. It can be a database query with many joins or even the result of a Federated search.
We want those data to be processed by various algorithm using one thread per algorithm. Every thread should have its own copy of the original instance, since using the same object will result to inconsistent results.

So we have an interface for representing the result of a Search.

package com.gkatzioura.design.creational.prototype;

public interface SearchResult {

    SearchResult clone();

    int totalEntries();

    String getPage(int page);
}

And we have the implementation of the SearchResult the FederatedSearchResult.

package com.gkatzioura.design.creational.prototype;

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

public class FederatedSearchResult implements SearchResult {

    private List<String> pages = new ArrayList<String>();

    public FederatedSearchResult(List<String> pages) {
        this.pages = pages;
    }

    @Override
    public SearchResult clone() {

        final List<String> resultCopies = new ArrayList<String>();
        pages.forEach(p->resultCopies.add(p));
        FederatedSearchResult federatedSearchResult = new FederatedSearchResult(resultCopies);
        return federatedSearchResult;
    }

    @Override
    public int totalEntries() {
        return pages.size();
    }

    @Override
    public String getPage(int page) {
        return pages.get(page);
    }
}

So we can use the clone method and create as many copies as we need of a very expensive object to create.

You can find the sourcecode on github.

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

Creational Design Patterns: Singleton Pattern

The singleton design pattern is a software design pattern the restricts the the instantiation of a class to one object.
In comparison with other creational design patterns such as the abstract factory, factory and the builder pattern the singleton will create an object but will also be responsible so that only one instance of that object exists.

When creating a class as a singleton there are some certain problems that is has to tackle.

  • How can it be ensured that a class has only one instance.
  • How can the sole instance of a class be accessed easily
  • How can a class control its instantiation
  • How can the number of instances of a class be restricted

 

Suppose we have a class that sends messages.
The Messenger class.

package com.gkatzioura.design.creational.singleton;

public class Messenger {

    public void send(String message) {
        
    }
}

However we want the message procedure to be handled only by one instance of the Messenger class. Imagine the scenario where the Messenger class opens a tcp connection (for example xmpp) and has to keep the connection alive in order to send messages. It will be pretty inefficient to open a new xmpp connection each time we have to sent a message.

Therefore we will proceed and make the messenger class a singleton.

package com.gkatzioura.design.creational.singleton;

public class Messenger {

    private static Messenger messenger = new Messenger();

    private Messenger() {}

    public static Messenger getInstance() {
        return messenger;
    }

    public void send(String message) {

    }
}

As you can see we set the messenger constructor as private, and we initialized a messenger using a static variable.
Static variables are class level variables, memory allocation only happens once when the class is loaded in the memory. By this way we ensure that the messenger class will be instantiated only once.
The getInstance method will fetch the static messenger instance once called.

Obviously the previous approach has its pros and cons.
We don’t have to worry on thread safety and the instance will be created only when the Messenger class will be loaded. However it lacks in flexibility. Consider the scenario of passing configuration variables to the Messenger constructor. It is not possible using the previous approach.

A workaround is to instantiate the messenger class on the getInstance method.

package com.gkatzioura.design.creational.singleton.lait;

public class Messenger {

    private static Messenger messenger;

    private Messenger() {}

    public static Messenger getInstance() {

        if(messenger==null) {
            messenger = new Messenger();
        }

        return messenger;
    }
    
    public void send(String message) {

    }
}

The above approach might work in certain case but it misses on thread safety in cases where the class might get instantiated in a multithreaded environment.

The easiest approach to make our class thread safe is to synchronize the getInstance method.

package com.gkatzioura.design.creational.singleton.lait;

public class Messenger {

    private static Messenger messenger;

    private Messenger() {}

    public synchronized static Messenger getInstance() {

        if(messenger==null) {
            messenger = new Messenger();
        }

        return messenger;
    }

    public void send(String message) {

    }
}

That one will work. At least the creation of the messenger will be synchronized and no duplicates will be created.
The problem with this approach is that the synchronization is only needed once when the object is created. Using the above code will lead to unnecessary overhead.

The other approach is to use the Double-Checked Locking approach. Now Double-Checked locking needs extra care since it is easy to pick the broken implementation over the correct one.
The best approach is to implement lazy loading using the volatile keyword.

package com.gkatzioura.design.creational.singleton.dcl;

public class Messenger {

    private static final Object lock = new Object();
    private static volatile Messenger messenger;

    private Messenger() {}

    public static Messenger getInstance() {

        if(messenger==null) {
            synchronized (lock) {
                if(messenger==null) {
                    messenger = new Messenger();
                }
            }
        }

        return messenger;
    }

    public void send(String message) {

    }
}

By using the volatile keyword we prevent the write of a volatile to be reordered with respect to any previous read or write and a read of a volatile to be reordered with respect to any following read or write.
Also a mutex object is used to achieve synchronization.

To sum up we created an object and we also made sure that there will be only one instance of that object. Also we made sure that there won’t be any problem on instantiating the object in a multi-threaded environment.

You can find the sourcecode on github.

On the next blog post we will have a look at the prototype pattern.

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

Creational Design Patterns: Builder Pattern

Previously we had a look at the factory and the abstract factory pattern. Those patterns serve their purpose and can be really useful however there are use cases where we have to create a very complex object and creating it requires different steps each one requiring different actions. In such cases the builder pattern can be really useful.
The builder design pattern is a creational design pattern and can be used in order to create complex objects step by step.

Supposing we have an object with many dependencies and in order to acquire each one these dependencies some certain actions have to be issued.
In such cases we can use the builder pattern in order to

  • Encapsulate creating and assembling the parts of a complex object in a separate Builder object.
  • Delegate the object creation to a Builder object instead of creating the objects directly.

Imagine the scenario of a backend system that has to compose and sent emails.
Creating an email might be a complex procedure. You have to specify the title, set the recipients, add a greeting add a closing statement. You might also want to use mustache instead. There is a wide range of options.

Having one class for all the actions needed to create an email might make our class bloated and loose its original purpose.

So we will start with the class responsible for sending the email.

package com.gkatzioura.design.creational.builder;

public class Email {

    private final String title;
    private final String recipients;
    private final String message;

    public Email(String title, String recipients, String message) {
        this.title = title;
        this.recipients = recipients;
        this.message = message;
    }

    public String getTitle() {
        return title;
    }

    public String getRecipients() {
        return recipients;
    }

    public String getMessage() {
        return message;
    }

    public void send() {

    }
}

As you can see the class contains only three string fields and there is no extra processing on them. So we shall create a builder class which will handle the message formatting, the recipient representation and the creation of the Email class.

package com.gkatzioura.design.creational.builder;

import java.util.HashSet;
import java.util.Set;

public class EmailBuilder {

    private Set recipients = new HashSet();
    private String title;
    private String greeting;
    private String mainText;
    private String closing;

    public EmailBuilder addRecipient(String recipient) {
        this.recipients.add(recipient);
        return this;
    }

    public EmailBuilder removeRecipient(String recipient) {
        this.recipients.remove(recipient);
        return this;
    }

    public EmailBuilder setTitle(String title) {
        this.title = title;
        return this;
    }

    public EmailBuilder setGreeting(String greeting) {
        this.greeting = greeting;
        return this;
    }

    public EmailBuilder setMainText(String mainText) {
        this.mainText = mainText;
        return this;
    }

    public EmailBuilder setClosing(String closing) {
        this.closing = closing;
        return this;
    }

    public Email create() {

        String message = greeting+"\n"+mainText+"\n"+closing;
        String recipientSection = commaSeparatedRecipients();

        return new Email(title,recipientSection,message);
    }

    private String commaSeparatedRecipients() {

        StringBuilder sb = new StringBuilder();
        for(String recipient:recipients) {
            sb.append(",").append(recipient);
        }

        return sb.toString().replaceFirst(",","");
    }

}

The next is step to make the email creation more strict so that creating an Email would only be possible through the EmailBuilder.

package com.gkatzioura.design.creational.builder;

import java.util.HashSet;
import java.util.Set;

public class Email {

    private final String title;
    private final String recipients;
    private final String message;

    private Email(String title, String recipients, String message) {
        this.title = title;
        this.recipients = recipients;
        this.message = message;
    }

    public String getTitle() {
        return title;
    }

    public String getRecipients() {
        return recipients;
    }

    public String getMessage() {
        return message;
    }

    public void send() {

    }

    public static class EmailBuilder {

        private Set recipients = new HashSet();
        private String title;
        private String greeting;
        private String mainText;
        private String closing;

        public EmailBuilder addRecipient(String recipient) {
            this.recipients.add(recipient);
            return this;
        }

        public EmailBuilder removeRecipient(String recipient) {
            this.recipients.remove(recipient);
            return this;
        }

        public EmailBuilder setTitle(String title) {
            this.title = title;
            return this;
        }

        public EmailBuilder setGreeting(String greeting) {
            this.greeting = greeting;
            return this;
        }

        public EmailBuilder setMainText(String mainText) {
            this.mainText = mainText;
            return this;
        }

        public EmailBuilder setClosing(String closing) {
            this.closing = closing;
            return this;
        }

        public Email build() {

            String message = greeting+"\n"+mainText+"\n"+closing;
            String recipientSection = commaSeparatedRecipients();

            return new Email(title,recipientSection,message);
        }

        private String commaSeparatedRecipients() {

            StringBuilder sb = new StringBuilder();
            for(String recipient:recipients) {
                sb.append(",").append(recipient);
            }

            return sb.toString().replaceFirst(",","");
        }

    }
}

The end result of using the builder pattern for creating an email will be like this.

Email email = new Email.EmailBuilder()
    .addRecipient("john@Doe.com")
    .setMainText("Check the builder pattern")
    .setGreeting("Hi John!")
    .setClosing("Regards")
    .setTitle("Builder pattern resources")
    .build();

To summarize by using the builder pattern we were able to create a complex object and its complex parts.

You can find the sourcecode on github.

On the next blog we will talk about the singleton pattern.

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

Creational Design Patterns: Factory Pattern

Previously we had an introduction to the Creational Patterns and used the Abstract Factory Pattern in order to create a families of objects.

The next pattern is the Factory Pattern. Factory pattern is one of the most used patterns when it comes to Java.
So what is the Factory Pattern all about? The factory pattern deals with creating objects without specifying the exact class or the object that will be created.

Let’s get into action by using the factory pattern for a Voucher problem.
Supposing we have a loyalty feature in our application which, depending on the customer’s transactions, rewards the customer with some vouchers.
The voucher requires a voucher code and since it will be displayed on the application it requires a specially formatted html message.

The first step is to create the voucher interface.

package com.gkatzioura.design.creational.factory;

public interface Voucher {

    public String code();

    public String htmlMessage();
}

We will have two types of Vouchers for now however it will be easy to add more once the business people come with more ideas.

The first one is the food Voucher.

package com.gkatzioura.design.creational.factory;

import java.util.UUID;

public class FoodVoucher implements Voucher {

    private UUID code;
    private static final String htmlMessage= "<html><body>
<h1>Food Voucher</h1>

</body></html>";

    public FoodVoucher() {
        code = UUID.randomUUID();
    }

    public String code() {
        return code.toString();
    }

    public String htmlMessage() {
        return htmlMessage;
    }
}

And the second one it the clothes voucher.

package com.gkatzioura.design.creational.factory;

import java.util.UUID;

public class ClothesVoucher implements Voucher {

    private UUID code;
    private static final String htmlMessage = "<html><body>
<h1>Clothes Voucher</h1>

</body></html>";

    public ClothesVoucher() {
        code = UUID.randomUUID();
    }

    public String code() {
        return code.toString();
    }

    public String htmlMessage() {
        return htmlMessage;
    }
}

The vouchers will be created based on a transaction-points system.
The food voucher will be created in cases of less than 30 transaction points. For transaction-points higher than 30 the clothes voucher shall be created.
So the next step is to create the mechanism that will create the vouchers based on the transaction points.
The best candidate for this is the Factory Pattern.

package com.gkatzioura.design.creational.factory;

public class VoucherFactory {

    public Voucher create(Integer discountPoints) {

        if(discountPoints<=0) {
            throw new IllegalArgumentException("Invalid number of discount points!");
        }

        if(discountPoints<30) {
            return new FoodVoucher();
        } else {
            return new ClothesVoucher();
        }
    }

}

To sum up by choosing the factory pattern

  • We create the vouchers needed without exposing to the client any creation logic.
  • The client does not have to specify the exact class of the object that will be created.

You can find the source code on github.

On the next blog post we will have a look at the builder pattern.

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