Monday, November 30, 2015

The Bridge design pattern

This tutorial presents the Bridge design pattern. Bridge is a structural pattern and allows the decoupling of an abstract class from its implementations. The pattern dictates the use of an interface between components, which  acts as a bridge and unbounds the abstraction from the implementation at compile time. This way both abstraction and implementations are independently extensible. Any possible changes in the implementation of the abstractions have no impact on the clients and in fact the implementation details are hidden from them (i.e., the clients).

To showcase the bridge pattern in a tutorial, let's consider electronic devices and remote controllers for handling such devices.  We have an abstraction representing the electronic devices and remote controllers. We use a bridge remote control interface between the electronic devices and the implementations of the remote controls. The UML class diagram is depicted in the following figure:



We start by the interface which all electronic devices implement and defines just on() and off() methods:
package com.tasosmartidis.design_patterns_tutorial.bridge;

public interface ElectronicDevice {

    public void on();
    
    public void off();  
}

We consider in our scenario two electronic devices, a TV and a radio. The Television class implements the ElectronicDevice inteface:
package com.tasosmartidis.design_patterns_tutorial.bridge;

public class Television implements ElectronicDevice {

    private boolean isOn = false;
    
    @Override
    public void on() {
        if(isOn)
            System.out.println("TV is already on, no action required!");
        else {
            System.out.println("Turning on TV...");
            isOn = true;
        }       
    }

    @Override
    public void off() {
        if(isOn) {
            System.out.println("Turning off TV...");
            isOn = false;
        }
        else
            System.out.println("TV is already off, no action required!");       
    }
}

And the Radio class does the same:
package com.tasosmartidis.design_patterns_tutorial.bridge;

public class Radio implements ElectronicDevice {

    private boolean isOn = false;
    
    @Override
    public void on() {
        if(isOn)
            System.out.println("Radio is already on, no action required!");
        else {
            System.out.println("Turning on radio...");
            isOn = true;
        }       
    }

    @Override
    public void off() {
        if(isOn) {
            System.out.println("Turning off radio...");
            isOn = false;
        }
        else
            System.out.println("Radio is already off, no action required!");        
    }

}

Now, we have our bridge abstract class. Electronic devices need remotes to be handled from far away. We consider that all remotes are providing three buttons,. Two of them are used for use of the on() and off() operations on electronic devices and a wild card button is left to the implementation of each remote controller to define its function. The ElectronicDevice class remote looks like this:
package com.tasosmartidis.design_patterns_tutorial.bridge;


public abstract class ElectronicDeviceRemote {

    private ElectronicDevice device;
    
    public ElectronicDeviceRemote(ElectronicDevice device) {
        this.device = device;
    }
    
    public void on() {
        this.device.on();
    }
    
    public void off(){
        this.device.off();
    }
    
    public abstract void wildCardDeviceButton(); 
}

Next, we will create two remotes, a cheap and an expensive one. We start with the cheap remote which doesn't really make use of the wild card button:
package com.tasosmartidis.design_patterns_tutorial.bridge;

public class CheapRemote extends ElectronicDeviceRemote {

    public CheapRemote(ElectronicDevice device) {
        super(device); 
    }
    
    public void wildCardDeviceButton() {
        System.out.println("Too cheap to use the button!");
    }
}

The expensive remote, uses the button to provide timer for turning off the electronic device:
ackage com.tasosmartidis.design_patterns_tutorial.bridge;


public class ExpensiveRemote extends ElectronicDeviceRemote {

    public ExpensiveRemote(ElectronicDevice device) {
        super(device); 
    }
    
    public void wildCardDeviceButton() {
        System.out.println("Automated swich-off of device in 5'");
        try {
            // Let's not wait for the whole 5'
            Thread.sleep(3000);
        } catch (InterruptedException e) { 
            e.printStackTrace();
        }
        super.off();
    }
}


Finally, let's see how our devices and remotes work in a demo application:
package com.tasosmartidis.design_patterns_tutorial.bridge;


public class BridgeDemo {

    public static void main(String[] args) {
        ElectronicDevice tv = new Television(); 
        ElectronicDevice radio = new Radio(); 
        
        ElectronicDeviceRemote expensiveRemote = new ExpensiveRemote(tv);
        ElectronicDeviceRemote anotherExpensiveRemote = new ExpensiveRemote(radio);
        ElectronicDeviceRemote cheapRemote = new CheapRemote(tv);
        
        System.out.println("TV with the expensive remote!");
        expensiveRemote.on();
        expensiveRemote.on();
        expensiveRemote.wildCardDeviceButton();
        expensiveRemote.off();
        System.out.println();
        
        System.out.println("TV with the cheap remote!");
        cheapRemote.on();
        cheapRemote.wildCardDeviceButton();
        cheapRemote.off();
        cheapRemote.off();
        System.out.println();
        
        System.out.println("Radio with the expensive remote!");
        anotherExpensiveRemote.on();
        anotherExpensiveRemote.wildCardDeviceButton();
        anotherExpensiveRemote.off();
        System.out.println();

    }
}

And running the application produces the following results:

The application produced the expected results and out bridge tutorial is completed. The project is available on GitHub.

Sunday, November 22, 2015

The Decorator design pattern

The Decorator is a structural design pattern and one of the so called "wrapper" patterns along with adapter, facade, proxy and bridge. The decorator allows new functionalities to be added to an object statically or dynamically without affecting the behavior of objects of the same class.  It is used often in cases where concrete implementations should be decoupled from responsibilities and behaviors or when subclassing to achieve modification is impractical/impossible. In simple terms, in the decorator pattern we wrap the object, add functionality to it and offer this new version for use.

To showcase an implementation of the decorator pattern in the tutorial, we will consider the construction of a house, which can be delivered as the simple (empty) building or with additional features such as being furnished, having jacuzzi and similar options. The UML class diagram for our tutorial is depicted in the following picture:

We start our tutorial with the 'House' interface which defines a single method, buildHouse()
package com.tasosmartidis.design_patterns_tutorial.decorator;

public interface House {

    void buildHouse();
}

The interface is implemented by classes which build either concrete
package com.tasosmartidis.design_patterns_tutorial.decorator;

public class ConcreteHouse implements House {

    public void buildHouse() {
        System.out.println("Building a concrete house...");     
    }
}
or wooden houses
package com.tasosmartidis.design_patterns_tutorial.decorator;

public class WoodenHouse implements House {

    public void buildHouse() {
        System.out.println("Building a wooden house...");       
    }
}

Next comes our decorator class which implements the House interface, but leaves the buildHouse() abstract so that different classes that extend the decorator class can implement the method adding new features (alternatively the method could be overridden). The code for the decorator class is shown below:
package com.tasosmartidis.design_patterns_tutorial.decorator;


public abstract class HouseDecorator implements House {

    protected House decoratedHouse;
    
    public HouseDecorator(House decoratedHouse) {
        this.decoratedHouse = decoratedHouse;
    }
    
    public abstract void buildHouse();
}

We will now define classes which add new features and decorate the basic construction of a house. We can delivered the house furnished
package com.tasosmartidis.design_patterns_tutorial.decorator;


public class FurnishedHouse extends HouseDecorator {

    public FurnishedHouse(House decoratedHouse) {
        super(decoratedHouse); 
    }
    
    public void buildHouse() {
        decoratedHouse.buildHouse();
        decorateWithFurniture();
    }
    
    private void decorateWithFurniture() {
        System.out.println("Adding furniture to the house...");
    }
}

as well as with jacuzzi for the people that want something more premium
package com.tasosmartidis.design_patterns_tutorial.decorator;


public class HouseWithJacuzzi extends HouseDecorator {

    public HouseWithJacuzzi(House decoratedHouse) {
        super(decoratedHouse); 
    }

    public void buildHouse() {
        decoratedHouse.buildHouse();
        decorateWithJacuzzi();
    }
    
    private void decorateWithJacuzzi() {
        System.out.println("Adding jacuzzi to the house...");
    }
}

So far, so good, now let's build some houses! We will create a demo application that builds a couple of houses using different decoration, as shown in the following code snippet:
package com.tasosmartidis.design_patterns_tutorial.decorator;

public class DecoratorDemo {

    public static void main(String[] args) {
        // Build a wooden house with furniture
        System.out.println("Wooden house with furniture:");
        House woodenHouse = new WoodenHouse();      
        House furnishedHouse = new FurnishedHouse(woodenHouse);     
        furnishedHouse.buildHouse();    
        
        System.out.println();
        
        // Build a concrete house with furniture and jacuzzi
        System.out.println("Concrete house with furniture & Jacuzzi:");
        House concreteHouse = new ConcreteHouse();
        House furnishedHouseWithJacuzzi = new HouseWithJacuzzi(new FurnishedHouse(concreteHouse));      
        furnishedHouseWithJacuzzi.buildHouse();

    }
}

Running the application yields the following output:












That's all folks! The code is as always available in GitHub.

Monday, November 16, 2015

The Proxy design pattern

In the previous tutorial we presented the facade design pattern. The facade pattern, along with the adapter (which was presented earlier), the proxy (this post) the decorator and bridge patterns (coming soon), are all essentially wrapping certain functionality and provide a different interface. The difference between them is in their intent.

The proxy design pattern is a structural one where a class (proxy) is used to represent and allow access to the functionality of another class. The proxy is often used to add behavior in certain functionality, to protect the class that is being proxied so it is not accessed and in general to control the access to a class. Motivations for its use can be that the proxied class is costly, and for creating intelligent and distributed access to the proxied class. The proxy class can substitute the class that it proxies.

In order to provide a simple tutorial and showcase the proxy pattern we will use the case of a company that helps agoraphobic people with their chores. Below is depicted the UML class diagram of the tutorial:

First we will create the an interface with a single method 'doChores()' which we all have to implement.
package com.tasosmartidis.design_patterns_tutorial.proxy;

public interface ChoreDoer {

    public void doChores();
}


Next we have the AgoraphobicPerson class who does chores but does not like to go out of the house. Also there is a method skypeWithFamily which for the purposes of the tutorial is considered to be costly and we do not want our proxy to provide access to it, as shown in the source code below:
package com.tasosmartidis.design_patterns_tutorial.proxy;

import java.util.Arrays;
import java.util.List;

public class AgoraphobicPerson implements ChoreDoer {
    private List<String> chores = Arrays.asList(new String[]{"grocery shopping" ,"taxes", "dog walking"});
    
    @Override
    public void doChores() {
        System.out.println("Getting my chores done while home!");
        for(String chore : chores) {
            System.out.println("Chore: " + chore);
        }
    }

    // Fun but let's say costly operation
    public void skypeWithFamily() {
        System.out.println("Skyping with family from home!");
    }
}


But our agoraphobic person will use a proxy for doing its chores and the ProxyAgent class of the agency in our scenario does that and also provides additional functionality, such as premium services with detailed report of the chore expenses:
package com.tasosmartidis.design_patterns_tutorial.proxy;

public class ProxyAgent implements ChoreDoer {

    private AgoraphobicPerson client;
    
    public ProxyAgent(AgoraphobicPerson client) {
        this.client = client;
    }
    
    @Override
    public void doChores() {
        this.client.doChores();
    }
    
    // Adding some extra functionality to provide report of the expenses
    public void doChoresExtra() {
        this.client.doChores();
        System.out.println("Providing detailed report of the chores made by agent!");
    }

}


Let's now use the proxy class to do the chores for the agoraphobic person in our demo
package com.tasosmartidis.design_patterns_tutorial.proxy;

public class ProxyDemo {

    public static void main(String[] args) {
        AgoraphobicPerson client = new AgoraphobicPerson();     
        ProxyAgent agent = new ProxyAgent(client);
        
        // Let's do the chores for our agoraphobic client via the proxy
        System.out.println("Basic services:");
        agent.doChores();
        
        System.out.println();
        
        // And provide the premium chore services
        System.out.println("Premium services:");
        agent.doChoresExtra();
    }
}


And running the demo gives us the following results:
















And this concludes our brief tutorial on the proxy design pattern! The code is available on GitHub.

Thursday, November 12, 2015

The Facade design pattern

From time to time I like to review code I developed in the past. It's nice to see how you would improve things at the level you are now and remember things that challenged you in a specific project. I was reviewing recently some classes I developed in a project that involved a lot of legacy code written by various developers and was a bit complex and messy. I used a facade to provide access to certain functionalities via a clear (and simple) API and had hidden behind it some classes I developed that were not so "pleasing to read" and worked with and capitalized the legacy code. The methods of the facade would be used by other components of the system written by another developer and I wanted to make his life easier. After the nostalgia, I though to write a tutorial on the Facade design pattern.

The facade design pattern is of the structural family and is used to provide a simple interface to clients, hiding the complexities of the operations it provides behind it. It also can be used to limit the dependencies with outside code on the internal of its application and to provide a well designed API over a poorly designed one.

To provide an example of its use, we will use a hotel reception. When a customer asks for a room it only interacts with the receptionist but a lot of activities are taking place, such as finding the available rooms, sending a cleaning crew (for our example) and retrieving funds from the customer. All these are transparent to the customer who only asks for a room and pays the receptionist in a single interaction. The UML class diagram of the demo we will develop in the tutorial is depicted in the figure below:


Let's start with the classes and functionalities that we want to make transparent and simplify the interaction with the customer. First let's create the FundsChecker class which examines if the client has enough money to book a room:
package com.tasosmartidis.design_patterns_tutorial.facade;

public class FundsChecker {

    public boolean checkIfEnoughMoney(double moneyFromClient) {
        if(moneyFromClient>30)
            return true;
        
        return false; 
    }
}

Our hotel is offering crazy deals, just 30 of some currency and we facilitate them! Next, lets write a class that finds the availability of the hotel rooms:
package com.tasosmartidis.design_patterns_tutorial.facade;

import java.util.Random;

public class RoomAvailabilityFinder {

private Random randomGenerator;
    
    public RoomAvailabilityFinder() {
        randomGenerator = new Random();
    }
    
    public int findAvailableRoom() {
        int emptyRoom = randomGenerator.nextInt(200);
        if(emptyRoom%2==0)
            System.out.println("Room " + emptyRoom + " is available");
        else {
            System.out.println("we are sorry, there are no available rooms!");
            emptyRoom = -1;
        }
        
        return emptyRoom;
    }
}

Apparently only even numbered rooms can be available in our hotel, but even numbered or not, the rooms must absolutely be clean! The CleaningCrew takes care of that:
package com.tasosmartidis.design_patterns_tutorial.facade;

public class CleaningCrew {

    public void cleanRoom(int roomNumber) {
        try {
            Thread.sleep(2000); // Good cleaning takes time!
            System.out.println("Room " + roomNumber +" is clean and ready!");
        } catch (InterruptedException e) { 
            e.printStackTrace();
        }
    }
}

Alright, all the necessary functionalities are in place. Now we want to simplify the interaction of the client with the reception. The client just wants a room and does not care who and how will arrange that for him. The ReceptionFacade class provides that simple interface, with a single method as shown below:
package com.tasosmartidis.design_patterns_tutorial.facade;


public class ReceptionFacade {

    private RoomAvailabilityFinder roomFinder;
    private CleaningCrew cleaningCrew;
    private FundsChecker fundsChecker; 
    
    public ReceptionFacade() {      
        
        roomFinder = new RoomAvailabilityFinder();
        cleaningCrew = new CleaningCrew();
        fundsChecker = new FundsChecker();
    }
    
    public void requestARoomOfMaximum(double clientMoney) {
        if(fundsChecker.checkIfEnoughMoney(clientMoney)) {
            int roomAvailable = roomFinder.findAvailableRoom();
            if(roomAvailable!=-1)
                cleaningCrew.cleanRoom(roomAvailable);
        }else {
            System.out.println("I am sorry there is not an available room for your funds!");
        }
    }
}

Our hotel is ready and will now receive its first potential clients! The demo class below presents how a client interacts with the hotel reception facade:
package com.tasosmartidis.design_patterns_tutorial.facade;


public class HotelDemo {

    public static void main(String[] args) {
        ReceptionFacade receptionist = new ReceptionFacade();
        
        System.out.println("First customer:");
        receptionist.requestARoomOfMaximum(15.00);
        System.out.println();
        System.out.println("Second customer:"); 
        receptionist.requestARoomOfMaximum(50.00);

    }

}


Running this demo application returns the following results:













This concludes the facade design pattern tutorial and the code is as usual available on GitHub. Cheers!

Tuesday, November 10, 2015

The Singleton design pattern

Last few weeks were quite busy so I did not have time to blog. Coming back, I would like to warm up with a quick and easy design pattern to add to the tutorial series, the Singleton design pattern. The Singleton design pattern is a creational one and is used to ensure that a single instance of a class is created and used by different applications, threads and similar. The singleton class has only one instance and provides global access to it.

To showcase this pattern we will imagine a poker table in our brand new 'Geek Casino'. A single deck of cards is used from which different players (in our case threads) are dealt.

First let's create a Card object which will be used by our Singleton CardsDeck later on. The card POJO is very simple, just the card number and the french suit (sidenote: here you can learn more about the origin of the french suit symbols)
package com.tasosmartidis.design_patterns_tutorial.singleton;

public class Card {

    private int number;
    private String frenchSuit;
    
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        if(number <13 && number>0)
            this.number = number;
    }
    public String getFrenchSuit() {
        return frenchSuit;
    }
    public void setFrenchSuit(String frenchSuit) {
        this.frenchSuit = frenchSuit;
    }
    
    @Override
    public String toString() {
        return number + "-of-" +  frenchSuit;
    }
    
    public int compare(Card c1, Card c2) {
        return c1.number - c2.number;
    }
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((frenchSuit == null) ? 0 : frenchSuit.hashCode());
        result = prime * result + number;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Card other = (Card) obj;
        if (frenchSuit == null) {
            if (other.frenchSuit != null)
                return false;
        } else if (!frenchSuit.equals(other.frenchSuit))
            return false;
        if (number != other.number)
            return false;
        return true;
    }

}

Next we create the singleton class (i.e., CardsDeck) by making its constructor private and providing a static method the provides the unique instance of the class in a synchronized block so that it is thread safe. We have a few methods to help us with our casino example such as initializing the deck, dealing cards and similar. The source code of the singleton class is presented below:
package com.tasosmartidis.design_patterns_tutorial.singleton;

import java.util.ArrayList;
import java.util.Random;

public class CardsDeck {

    private static CardsDeck uniqueInstance = null;
    
    private ArrayList<Card> deckOfCards = createCardDeck();
    
    static boolean firstThread = true;
    
    // private non-accessible constructor
    private CardsDeck() {}
    
    // the static method that provides the unique instance of the class at any point of the execution
    public static CardsDeck getInstance() {
        
        if(uniqueInstance==null) {
            
            // make the access to the singleton thread-safe
            synchronized(CardsDeck.class) {
                if(uniqueInstance==null)
                    uniqueInstance = new CardsDeck();           
            }
        }
        
        return uniqueInstance;
    }
    
    public ArrayList<Card> getCardsOfDeck() {
        return uniqueInstance.deckOfCards;
    }
    
    public ArrayList<Card> getCardsForPlayer(int numberObCards) {
        ArrayList<Card> playersCards = new ArrayList<>();
        Random random = new Random();
        
        for(int i=0;i<=numberObCards;i++) {
            // Just provide index of a card within range 5-14 to deal to the player. 
            // We assume there would be at least 10 cards in the deck always to keep code simple 
            int cardIndex = random.nextInt(15-5) + 5;
            
            playersCards.add(uniqueInstance.deckOfCards.remove(cardIndex));
        }
        
        return playersCards;
    }
    
    // Methods to initialize our deck of cards to play with
    private ArrayList<Card> createCardDeck() {
        ArrayList<Card> deckOfCards = new ArrayList<>();
        
        String[] frenchSuits = new String[]{"hearts","diamonds","spades","clubs"};
        
        for(String suit : frenchSuits) {
            for(int i=1;i<13;i++) {
                Card newCard = new Card();
                newCard.setFrenchSuit(suit);
                newCard.setNumber(i);
                deckOfCards.add(newCard);
            }
        }
        
        return deckOfCards;
    }
}

Next, we will create a Runnable for dealing cards to player so that later in our demo we can ask cards from the deck via different threads. The GetCardsRunnable implements the Runnable interface as shown below:
package com.tasosmartidis.design_patterns_tutorial.singleton;

import java.util.ArrayList;


public class GetCardsRunnable implements Runnable {

    private String runnableName;
    
    public GetCardsRunnable(String runnableName) {
        this.runnableName = runnableName;
    }
    
    @Override
    public void run() {
        CardsDeck cardsDeck = CardsDeck.getInstance();
        
        System.out.println("Casino ID: " + System.identityHashCode(cardsDeck));
        System.out.println(cardsDeck.getCardsOfDeck());
        
        ArrayList<Card> playerOneCards = cardsDeck.getCardsForPlayer(5);
        System.out.println("Player '" + this.runnableName + "' has: " + playerOneCards);
        
        System.out.println("Cards were dealt!");
        System.out.println();
        
    }

}

Now we can create a simple main method where we will use two of the above Runnables to deal cards from the deck and evaluate how our singleton class works:
package com.tasosmartidis.design_patterns_tutorial.singleton;


public class Casino {

    public static void main(String[] args) {
        Runnable player1Thread = new GetCardsRunnable("player1");
        Runnable player2Thread = new GetCardsRunnable("player2");
        
        new Thread(player1Thread).start(); 
        new Thread(player2Thread).start();
    }

}


Finally let's how our Singleton will work for two players (threads) asking to be dealt by the deck. It should be the same deck, so the cards dealt for the first player should not be available when dealing the second. And indeed as you can see in the figure below, cards dealt to the first player (e.g., 8 of hearts) are not in the deck when dealing to the second.

The 'Casino ID' also shows the hashcode of the CardsDeck object, which as the reader can see is the same. This concludes our short tutorial on the Singleton design pattern. The code is available on GitHub. Comments or questions are welcomed and more tutorials are coming!