External Iterator for Composite

We have seen how the composite pattern could be used to implement a sort of extended iterator to navigate in a structure of menus and submenus. Now we want to go a bit further, and use an external iterator, a quite more complex pattern.

To see it in action, we'll extend the already seen example, so that we'll be able to print menus on the fly, browsing through the elements available and selecting the items matching his own current request.

Using an external iterator we would be able to keep the current position of iteration and keep the current position over the recursive structure of a composite collection.

Here is our new iterator:
import java.util.Iterator;
import java.util.Stack;

class IteratorComposite implements Iterator {
    Stack<Iterator<MenuComponent>> stack = new Stack<Iterator<MenuComponent>>();

    public IteratorComposite(Iterator<MenuComponent> iterator) { // 1
        stack.push(iterator);
    }

    public boolean hasNext() { // 2
        // check if there are element left on the stack
        if(stack.empty())
            return false;

        // check if the current menu has a next element
        Iterator<MenuComponent> it = stack.peek();
        if(it.hasNext())
            return true;

        // no next element in the current element, check the next one
        stack.pop();
        return hasNext();
    }

    public MenuComponent next() { // 3
        if(hasNext() == false)
            return null;

        Iterator<MenuComponent> it = stack.peek();
        MenuComponent mc = it.next();
        if(mc instanceof Menu)
            stack.push(mc.iterator());
        return mc;
    }

    public void remove() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
Not the simplest piece of code in the world, actually.
1. The client starts a request, passing an iterator to the item where we want to begin the job. Since we have to manage a tree structure, we use a stack to keep memory of the various levels we could find.
2. To check if there is a next element, we check (a) if the stack is empty - if so, naturally there we'll be no next, and (b) if the current element in the stack has a next - if so we can just return true. Moreover, if (c) the current element has no next, we can just pop it from the stack - there is no more use for it - and enter in a recursion.
3. Before returning the next element, we check if it actually exists. The client should always do this check on its own, so this check is a bit redundant. Looks like we lack of trust in the client. In any case, we peek in the stack for the current iterator, and we get its next element. If it is a Menu, we push on the stack its iterator, since we'll have to get the future next from it. Finally we return what we found.

To keep the code not even more complex we use a Null Iterator, a paradigm similar to the Null Object we have already seen before. MenuItem has nothing to iterate, so we usually return a null when the client ask it for a iterator, and let it to manage this asymmetry. If we return an iterator that never has a next, and if we still call for next, it returns us a null, the code gets less complicated:
import java.util.Iterator;
class IteratorNull implements Iterator {
    public boolean hasNext() {
        return false;
    }

    public MenuComponent next() {
        return null;
    }

    public void remove() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
Let's refactor the MenuComponent class adding a method for retrieving its iterator that, by default, return the Null Iterator and change accordingly the derived classes that do return a real iterator - in our case, just the Menu class:
public abstract class MenuComponent {
    // ...
    // common method
    public void print() {
        throw new UnsupportedOperationException();
    }

    public Iterator<MenuComponent> iterator() {
        return new IteratorNull();
    }
}

public class Menu extends MenuComponent {
    // ...
    @Override
    public Iterator iterator() {
        return new IteratorComposite(components.iterator());
    }
}
We still have to change the Waitress class, to add a method using the iterator. Here we have a method for printing just and all the vegetarian dishes available:
public void printVeggieMenu() {
    System.out.println("\nVeggie Menu\n");
    int i = 0;

    Iterator<MenuComponent> it = menus.iterator();
    while(it.hasNext()) {
        MenuComponent mc = it.next();

        if(mc instanceof MenuItem) {
            if(mc.isVeg())
                mc.print();
        }
    }
}
We see in the code a check on the type for the object returned by the iterator, to resolve the transparency added by the composite, since here we actually want to do an operation that makes sense only for MenuItem. The alternatives are try/catching on the call to isVeg() - for a Menu we'll have an exception, or implementing isVeg() also for menu, making it returning always false.

I'm not especially happy with this code. I think I would have taken a different way, something like providing an iterator that would return just MenuItem. I see this is not a clean solution either, since it violates the transparency principle for a composite. But a violation somewhere there has to be, given the problem we are facing, and I will be more comfortable explicitly putting the violation in the class interface, instead of letting Waitress class the burden of messing with it.

In any case, I suggest you to read chapter nine of Head First Design Patterns to have more info on this pattern, and make yourself your idea.

Go to the full post

Composite

The Composite Pattern is used to model tree structures representing part-whole hierarchies, letting the client treats individual objects and compositions of objects in a uniform way.

The client refers to the class object of its request through the Component interface, that is implemented by all the objects in the composition. An element in the composition that has no children is a Leaf. The Composite is an element in the composition that do haves children.

The issue with this approach is that it violates the Single Responsibility Design Principle, since we put two responsibilities in one class and, worse, we rely on the fact that some methods shouldn't be used accordingly to the usage of the actual object.

The point is that we trade safety for transparency. In this way the client could treat composites and leaf operations at the same way; but it should take care of not mistaking one for the other.

As example of usage for the Composite Patter we see a rewrite of the menus management system we have seen when we talked about the Iterator Pattern. Suppose that we have a change request: we should be able to add sub-menus to a menu. In the specific case, we want that our dinner menu has associated a dessert menu.

To do that we decide to base our class hierarchy on the MenuComponent class in this way:
public abstract class MenuComponent { // 1
    // 2. composite operation methods
    public void add(MenuComponent component) {
        throw new UnsupportedOperationException();
    }

    public void remove(MenuComponent component) {
        throw new UnsupportedOperationException();
    }

    public MenuComponent getChild(int i) {
        throw new UnsupportedOperationException();
    }

    // 3. operation methods
    public String getName() {
        throw new UnsupportedOperationException();
    }

    public String getDescr() {
        throw new UnsupportedOperationException();
    }

    public double getPrice() {
        throw new UnsupportedOperationException();
    }

    public boolean isVeg() {
        throw new UnsupportedOperationException();
    }

    // 4. common method
    public void print() {
        throw new UnsupportedOperationException();
    }
}
1. the class is abstract: we can't actually instantiate MenuComponent object.
2. add(), remove(), getChild() are methods for the composite branch of the hierarchy, the operation should not redefine them, giving an exception to the client if it wrongly try to use them.
3. getName(), getDescr(), getPrice(), and isVeg() are methods for the operation leaves. They don't make any sense for the component objects.
4. print() is a common method, should implemented for all the actual objects. In case of Composite, it should just call the print method for all the leaves associated to it.

In this new architecture, the MenuItem is implemented in this way:
public class MenuItem extends MenuComponent {
    private String name;
    private String descr;
    private boolean veg;
    private double price;

    public MenuItem(String name, String descr, boolean veg, double price) {
        this.name = name;
        this.descr = descr;
        this.veg = veg;
        this.price = price;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getDescr() {
        return descr;
    }

    @Override
    public double getPrice() {
        return price;
    }

    @Override
    public boolean isVeg() {
        return veg;
    }

    @Override
    public void print() {
        System.out.print(" " + getName());
        if(isVeg()) {
            System.out.print("(v)");
        }
        System.out.print(", " + getPrice());
        System.out.println(" --- " + getDescr());
    }
}
Only the methods that actually make sense are implemented here; same structure for the class Menu:
public class Menu extends MenuComponent {
    ArrayList<MenuComponent> components = new ArrayList<MenuComponent>(); // 1
    String name;
    String descr;

    public Menu(String name, String descr) {
        this.name = name;
        this.descr = descr;
    }

    @Override
    public void add(MenuComponent mc) {
        components.add(mc);
    }

    @Override
    public void remove(MenuComponent mc) {
        components.remove(mc);
    }

    @Override
    public MenuComponent getChild(int i) {
        return components.get(i);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getDescr() {
        return descr;
    }

    @Override
    public void print() {
        System.out.print("\n" + getName());
        System.out.println(", " + getDescr());
        System.out.println("----------------");

        for(MenuComponent mc: components) { // 2
            mc.print();
        }
    }
}
1. we change a bit the Menu from the original implementation. Now it has a list of the owned sub-elements, and it keeps track of its own name and description.
2. here the print() implementation relies on the sub-elements print(). We use implicitly the Iterator Pattern via the handy Java 5 "for" construct.

Since we moved most of the logic for the management of the menus inside the relative classes - and it makes a lot of sense, thinking about it - the waitress class is now a lot simpler:
public class Waitress {
    MenuComponent menus;

    public Waitress(MenuComponent menus) {
        this.menus = menus;
    }

    public void printMenu() {
        menus.print();
    }
}
And here is the sample code for testing our new application:
MenuComponent menuPancake = new Menu("Pancake", "Breakfast");
MenuComponent menuDiner = new Menu("Diner", "Lunch");
MenuComponent menuCafe = new Menu("Café", "Dinner");
MenuComponent menuDessert = new Menu("Dessert", "After Dinner Dessert");

menuPancake.add(new MenuItem("M1 Pancake", "Sausage pancake", false, 2.99));
menuPancake.add(new MenuItem("V1 Pancake", "Veggie pancake", true, 2.99));
menuPancake.add(new MenuItem("V2 Pancake", "Blueberry pancake", true, 3.49));
menuPancake.add(new MenuItem("V3 Pancake", "Waffle", true, 3.49));
menuDiner.add(new MenuItem("V1 Diner", "Veggie stuff", true, 2.99));
menuDiner.add(new MenuItem("M1 Diner", "Hamburger", false, 2.99));
menuDiner.add(new MenuItem("M2 Diner", "Soup", false, 3.49));
menuDiner.add(new MenuItem("M3 Diner", "Hotdog", false, 3.99));
menuCafe.add(new MenuItem("M1 Cafè", "FatBurger", false, 4.99));
menuDessert.add(new MenuItem("D1 Cafè", "Apple Pie", true, 1.59));

MenuComponent menuAll = new Menu("All menus", "The complete offer");
menuAll.add(menuPancake);
menuAll.add(menuDiner);
menuAll.add(menuCafe);

menuCafe.add(menuDessert);

Waitress w = new Waitress(menuAll);
w.printMenu();
More on this pattern in chapter eight of Head First Design Patterns. This post is just the result of my reading and taking some memo from it.

Go to the full post

Iterator

Through the Iterator pattern we can access sequentially all the elements of an aggregate object without exposing its underlying representation. The Iterator takes over from the aggregate the responsibility of traversing it, simplifying the aggregate interface and implementation.

The classic methods provided by an iterator are: first(), next(), isDone(), and currentItem(). Typically in Java these four methods are reduced to: next() and hasNext(); and java.util.Iterator sports even a remove() method used to modify the undelying data.

In my humble opinion adding remove() in the standard java.util.Iterator has not been a wonderful idea. Notice that the API documentation says remove() is a optional operation so an UnsupportedOperationException could be thrown if it is not implemented. Besides, we could get an IllegalStateException if the iterator has problem in performing the operation.

Not considering remove(), the fundamental difference in the two sets of operation is that the second does not have a way to get back to the beginning of the collection, since there is no first() method or anything equivalent. So this kind of iterators are basically for one time usage.

The first implementation of the Iterator pattern in Java is java.util.Enumerator, still available for compatibility reason but not much used nowadays. It provides just two methods, hasMoreElements() and nextElements(), equivalents to hasNext() and next().

In the typical Java implementation of Iterator, hasNext() checks if there are more elements in the collection, and next() returns the next one. Since at creation an iterator is pointing to the fake position before the first element, calling next() at that moment would return the first element of the collection, if available.

Here is an example where the Iterator pattern comes in handy: we need to manage two menues that are very similar, are based on the same class, MenuItem, but they rely on different data structure. The class Waitress should print the list of the items available for both of them, MenuPancake and MenuDiner. But, since one is using an ArrayList and the other a low level array, looks like there is no way of access the two collections in the same way.

As usual in computer sciences, we solve the problem introducing an extra layer. And in this case this role is played by the iterator. We don't access directly the collections, but we use iterators to them. It would be each iterator task taking care of the low level details, exposing to the client just the common behavior.

The core of our system is the item used to describe the dish on the menu, the MenuItem class:
public class MenuItem {
    private String name;
    private String descr;
    private boolean veg;
    private double price;

    public MenuItem(String name, String descr, boolean veg, double price) {
        this.name = name;
        this.descr = descr;
        this.veg = veg;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public String getDescr() {
        return descr;
    }

    public double getPrice() {
        return price;
    }

    public boolean isVeg() {
        return veg;
    }
}
Besides the usage of this basic data structure, we are asking to our menus only to give us a way to access its items through an iterator. We make explicit this requirement saying that any menu should implement this interface:
import java.util.Iterator;

public interface Menu {
    public Iterator iterator();
}
An interesting point is that the Pancake menu is using an ArrayList collection, and that makes available its own iterator that we can use for our needing. But the Diner menu is using a raw array that, as one could expect, does not provide such a fancy feature like an iterator.

We solve this issue providing a custom iterator for this case:
import java.util.Iterator;

public class IteratorDiner implements Iterator {
    MenuItem[] menu;
    int pos = 0;

    public IteratorDiner(MenuItem[] menu) {
        this.menu = menu;
    }

    public boolean hasNext() {
        if(pos < menu.length && menu[pos] != null)
            return true;
        else
            return false;
    }

    public MenuItem next() {
        return menu[pos++];
    }

    public void remove() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
I'm not interested in activating the remove() support in this iterator, so I leave it throwing an exception.

So, here is our pancake menu:
import java.util.ArrayList;
import java.util.Iterator;

public class MenuPancake implements Menu {
    private ArrayList<MenuItem> menu;

    public MenuPancake() {
        menu = new ArrayList<MenuItem>();
        add("M1", "Sausage pancake", false, 2.99);
        add("V1", "Veggie pancake", true, 2.99);
        add("V2", "Blueberry pancake", true, 3.49);
        add("V3", "Waffle", true, 3.49);
    }

    public final void add(String name, String desc, boolean veg, double price) {
        MenuItem item = new MenuItem(name, desc, veg, price);
        menu.add(item);
    }

    public Iterator iterator() {
        return menu.iterator();
    }
// ...
}
And this is the diner menu:
import java.util.Iterator;

public class MenuDiner implements Menu {
    private static final int MAX_ITEMS = 6;
    private int nrItems = 0;
    private MenuItem[] menu;

    public MenuDiner() {
        menu = new MenuItem[MAX_ITEMS];

        add("V1", "Veggie stuff", true, 2.99);
        add("M1", "Hamburger", true, 2.99);
        add("M2", "Soup", true, 3.49);
        add("M3", "Hotdog", true, 3.99);
    }

    public final void add(String name, String desc, boolean veg, double price) {
        if (nrItems < MAX_ITEMS) {
            menu[nrItems++] = new MenuItem(name, desc, veg, price);
        } else {
            System.err.println("Can't add more items to the menu!");
        }
    }

    public Iterator iterator() {
        return new IteratorDiner(menu);
    }

    // ...
}
In this way the Waitress class is not interested in the implementation details of its client classes, it just relies on the iterator:
import java.util.Iterator;

public class Waitress {
    private Menu menuDiner;
    private Menu menuPancake;

    public Waitress(MenuDiner menuDiner, MenuPancake menuPancake) {
        this.menuDiner = menuDiner;
        this.menuPancake = menuPancake;
    }

    public void printMenu() {
        Iterator itPancake = menuPancake.iterator();
        System.out.println("Menu breakfast:");
        printMenu(itPancake);

        Iterator itDiner = menuDiner.iterator();
        System.out.println("Menu lunch:");
        printMenu(itDiner);
    }

    private void printMenu(Iterator it) {
        while(it.hasNext()) {
            MenuItem item = (MenuItem)it.next();
            System.out.print(item.getName() + ", ");
            System.out.print(item.getPrice() + " -- ");
            System.out.println(item.getDescr());
        }
    }
}
To test the code I wrote this few lines:
MenuDiner mDiner = new MenuDiner();
MenuPancake mPancake = new MenuPancake();

Waitress w = new Waitress(mDiner, mPancake);
w.printMenu();

If you want to get more details on the iterator pattern, I suggest you to read chapter nine of Head First Design Patterns. I jotted down this lines while reading it.

Go to the full post

The Hollywood Principle

The Hollywood Principle says: don't call us, we'll call you.

The sense of it is that we want our system having a clear path in dependency, to avoid the so called "dependency rot" where it looks like no one was really in control and any component is relying on someone else.

Accordingly to the Hollywood Principle the high-level component in our system controls when and how things happen. The low-level components can participate in the computation, but always under the control of the high-level one.

We can see this behavior in the Template Method pattern. There we have the high level component ruling the execution and its subclasses merely providing implementation details.

Chapter eight of Head First Design Patterns gives a good detailed introduction to this pattern. I'd suggest you to have a good read to the actual book, if you are interested in the matter.

Go to the full post

Template Method

The Template Method is discussed in chapter eight of Head First Design Patterns, here is some notes on this pattern that I jotted down while I was reading that fun book.

This pattern defines the structure of an algorithm in a method, deferring the implementation of some of its steps to the subclasses. In this way we have a defined algorithm that could be partially redefined in its subclasses.

We define an AbstractClass in which we have a templateMethod() and a few abstract method primitiveOperationX(), where X is in [1..n]. Each ConcreteClass extending AbstractClass would implement the primitive operations, giving its own version of the original template method.

As an example we see an application that emulates the generation of coffee and tea cups. For this beverages the recipes are very close, but not identical. Using the Template Method pattern we can extract the similarity in a base class and let the derived classes complete the job.

The abstract class:
public abstract class CaffeineBeverage {
    public final void prepare() { // 1
        boilWater();
        brew();
        pour();
        if(extrasRequired()) // 4
            addExtras();
    }

    protected abstract void brew(); // 2
    protected abstract void addExtras();

    private void boilWater() { // 3
        System.out.println("boiling water");
    }

    private void pour() {
        System.out.println("pour");
    }

    protected boolean extrasRequired() { // 4
        return true;
    }
}
1. prepare() is the templateMethod. It is declared final, since we don't want the subclass to redefine it.
2. brew() and addExtras() are primitiveOperations, they are abstract and so they have to be defined by the derived classes.
3. boilWater() and pour() are static parts of the algorithm, so they are private method of this class, they can't be changed by the derived classes.
4. extrasRequired() is a hook. A hook is method that has a default implementation in the AbstractClass but could be redefined by a ConcreteClass to provide a variation in the template method.


Any derived class from the AbstractClass has just to override the primitive operations. The rest of the job is done by the AbstractClass. Let's see a couple of them:
public class Coffee extends CaffeineBeverage {
    private boolean extras;

    public Coffee(boolean extras) {
        this.extras = extras;
    }

    @Override
    protected boolean extrasRequired() { // 1
        return extras;
    }

    @Override
    protected void brew() {
        System.out.println("dripping coffee through filter");
    }

    @Override
    protected void addExtras() {
        System.out.println("adding sugar and milk");
    }
}

public class Tea extends CaffeineBeverage {
    @Override
    protected void brew() {
        System.out.println("steeping the tea");
    }

    @Override
    protected void addExtras() {
        System.out.println("adding lemon");
    }
}
1. the Coffee class redefine the hook, providing a way to decide if the object should have extras.

Go to the full post

Principle of Least Knowledge

The Principle of Least Knowledge says that you should talk only to your immediate friends. Or: any class should have only a limited number of connections to other classes.

The point in this is that more relations we have among classe more difficult would be to maintain and change the system.

For instance, a pattern like Façade help us in simplify the relations among classes, and this is making our system simpler and more flexible.

Go to the full post

Façade

The Façade Pattern provides a higher level, unified interface to a set of interfaces in a subsystem with the intent of making it easier to use. The second part of chapter seven of Head First Design Patterns would tell you more on this pattern, here I write a few lines on it.

As example of usage of the Façade Pattern we can think of a complex system emulating a home theater. It consists of an Amplifier connected with a Tuner, a CD Player, a DVD Player. The DVD Player has to be connected to a Projector, and we'll also have a Screen, a Theater Light Manager and even a Popcorn Popper.

A cool system, indeed. But it requires quite a while to run. Watching a movie is not an easy task. Even if we have a standard procedure we know we are about to execute each time (starting with turning on the popcorn popper, ending with actually starting the DVD Player), we have no logical place where to store it for subsequent usage.

Well, the idea of the Façade Pattern is exactly to provide such a place.

In our specific case, we would create a class HomeTheaterFacade that would make available to the client a few methods, like watchMovie(), endMovie(), listenCD(), endCD() ..., that would let us access the system in a standard way taking care of the details.

The HomeTheaterFacade is just a shortcut to the Home Theater classes. We still have access to the original classes so, for instance, we can access the DVD Player to skip over a scene we find boring.

Go to the full post

Class and Object Adapter

The Adapter Pattern converts the interface of a class in another interface, to match the requirements of a client class. In this way an Adapted helps classes to work together even though they were not designed for that, and they don't have compatible interfaces.

In the Object Adapter Pattern, the Client expects a Target interface, providing a request() method. So the Adapter implements that interface and it is composed with the Adaptee class. The request() in the Adapter would use specific methods of the Adaptee class to perform its duty.

The Class Adapter Pattern makes use of Multiple Inheritance, and so it can't be used if Java is our implementation language. The difference is that we don't design the Adaptor class to have internally a reference to an Adaptee object, but it would actually derive publicly from it.

I have written this post while I was reading the first part of chapter seven of Head First Design Patterns, there you would find more information on the matter.

The example for the Adapter Patter is based on a change request for our system that emulates ducks quacking and flying. Now we want to adapt turkeys to be used instead ducks for the same tasks.

We have an existing Duck hierarchy:
public interface Duck {
    public void quack();
    public void fly();
}

public class DuckMallard implements Duck {
    public void quack() {
        System.out.println("quack!");
    }

    public void fly() {
        System.out.println("flying");
    }
}
And we have a different bird that we want to use as it would be a duck:
public interface Turkey {
    public void gobble();

    public void shortFly();
}
To do that we use this turkey adapter:
public class TurkeyAdapter implements Duck {
    Turkey turkey;

    public TurkeyAdapter(Turkey turkey) {
        this.turkey = turkey;
    }

    public void quack() {
        turkey.gobble();
    }

    public void fly() {
        for(int i = 0; i < 5; ++i)
            turkey.shortFly();
    }
}
This short function accepts in input a duck and makes it flying and quacking:
static void testDuck(Duck d) {
    d.fly();
    d.quack();
}

Here is a few lines of a tester for the adapter:
Duck duck = new DuckMallard();
Turkey turkey = new TurkeyWild();
Duck duckFake = new TurkeyAdapter(turkey);

System.out.println("Duck:");
testDuck(duck);

System.out.println("Turkey:");
turkey.shortFly();
turkey.gobble();

System.out.println("Turkey faking a duck:");
testDuck(duckFake);

Go to the full post

Command

The idea of Command Pattern is to encapsulate a request in an object. We do that when we want other objects to have access to a number of requests in parametrical form. Besides, using this pattern we could also support undoable operations.

You could read a good description of this pattern, using Java as implementation language, on chapter six of Head First Design Patterns.

We typically define an interface, Command is its name in the pattern, that defines a couple of methods, execute() and undo(), that would be implemented by each ConcreteCommand.

A ConcreteCommand would define the execute() method calling one or more actions on another class (named Receiver in this context).

A Client is responsible for creating a ConcreteCommand and setting its Receiver.

An Invoker would keep a Command, and call its execute() method when required.

As an example of a situation where the Command Pattern could work well, we have a remote control emulation. We have seven slot in it, each of them could be associated with a different device, any slot is associated with a couple of buttons (on and off), each button would carry on a specific task. Besides we have an undo button that undoes the last pressed button.

In this case the Receiver would be the class implementing the features on which the remote control would actually work. For instance, we could have a class for the lights in the house that could be turned on and off:
public class Light {
   private String room;

   public Light(String room) {
      this.room = room;
   }

   public void on() {
      System.out.println(room + " lights are on");
   }

   public void off() {
      System.out.println(room + " lights are off");
   }
}
Here is the hierarchy of commands, with a couple of ConcreteCommands that refer to Light, our Receiver, and a Null Object, idiom described in the previous post:
public interface Command {
   public void execute();
   public void undo();
}

public class CommandLightOff implements Command {
   private Light light;

   public CommandLightOff(Light light) {
      this.light = light;
   }

   public void execute() {
      light.off();
   }

   public void undo() {
      light.on();
   }
}

public class CommandLightOn implements Command {
   private Light light;

   public CommandLightOn(Light light) {
      this.light = light;
   }

   public void execute() {
      light.on();
   }

   public void undo() {
      light.off();
   }
}

public class NoCommand implements Command {
   public void execute() {
      System.out.println("No command implemented");
   }

   public void undo() {
      System.out.println("No command implemented");
   }
}
The command interface declares that any ConcreteCommand should define how to execute and undo its own action.

And now it's time to implement the Invoker:
public class RemoteControl {
   public static enum Slot { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN }
   private static int SLOT_NR = Slot.values().length; // 1

   private Command[] cmdOn;
   private Command[] cmdOff;
   Command last;

   public RemoteControl() { // 2
      cmdOn = new Command[SLOT_NR];
      cmdOff = new Command[SLOT_NR];

      Command noc = new NoCommand();
      for(int i = 0; i < SLOT_NR; ++i) {
         cmdOn[i] = noc;
         cmdOff[i] = noc;
      }
      last = noc;
   }

   public void setCommand(Slot slot, Command on, Command off) { // 3
      cmdOn[slot.ordinal()] = on;
      cmdOff[slot.ordinal()] = off;
   }

   public void pushOn(Slot slot) {
      last = cmdOn[slot.ordinal()];
      last.execute();
   }

   public void pushOff(Slot slot) {
      last = cmdOff[slot.ordinal()];
      last.execute();
   }

   public void pushUndo() {
      last.undo();
   }
}
1. I used enum to give the class a bit more robustness. The SLOT_NR constant is just a shorthand that makes the code a bit clearer. To change the number of slots available on the remote control is enough to define the name for a new slot in the enumeration.
2. The constructor creates the arrays for the on/off commands and initialize them using the Null Object. A better thought remote control would probably load its state from a configuration file.
3. We use setCommand() to define the action to be taken when an on/off button is pushed for a specific slot. To actually get the action related to the pushing of a button we have to call the pushOn()/pushOff() methods. To undo we have the pushUndo() method.

Finally, here is the client code that performs also a bit of testing:
RemoteControl rc = new RemoteControl();
rc.pushOn(RemoteControl.Slot.ONE);

Light lk = new Light("Kitchen");
Command klon = new CommandLightOn(lk);
Command kloff = new CommandLightOff(lk);

rc.setCommand(RemoteControl.Slot.ONE, klon, kloff);
rc.pushOn(RemoteControl.Slot.ONE);
rc.pushOff(RemoteControl.Slot.ONE);
rc.pushOn(RemoteControl.Slot.SEVEN);
rc.pushUndo();

Light lb = new Light("Bedroom");
Command blon = new CommandLightOn(lb);
Command bloff = new CommandLightOff(lb);
rc.setCommand(RemoteControl.Slot.SEVEN, blon, bloff);

for(RemoteControl.Slot cmd : RemoteControl.Slot.values())
   rc.pushOn(cmd);
rc.pushUndo();

Macro Command

We can extend our remote control to execute more action with a single click. The trick is based on this class:
public class MacroCommand implements Command {
   Command[] commands;

   public MacroCommand(Command[] commands) {
      this.commands = commands;
   }

   public void execute() {
      for(Command c : commands)
         c.execute();
   }

   public void undo() {
      for(Command c : commands)
         c.undo();
   }
}
The idea is quite simple: we construct the MacroCommand passing an array of commands. The MacroCommand.execute() would call execute() on each command in the array. And we apply the same strategy for undo().

To check the macro usage we add to our test client other few lines:
Command[] lightsOn = new Command[2];
lightsOn[0] = klon;
lightsOn[1] = blon;

Command[] lightsOff = new Command[2];
lightsOff[0] = kloff;
lightsOff[1] = bloff;

MacroCommand mcOn = new MacroCommand(lightsOn);
MacroCommand mcOff = new MacroCommand(lightsOff);

rc.setCommand(RemoteControl.Slot.SIX, mcOn, mcOff);
rc.pushOn(RemoteControl.Slot.SIX);
rc.pushUndo();
The call to pushOn() for the slot 6 would turn on the lights in both the registered rooms, and the undo would turn them off.

Go to the full post

Null Object

A null pointer is used often as a way to signal to the client code that a called method could not return any valid object to its request.

This makes sense, but if the client forgets to check about the validity of the returned pointer there could be catastrophic results such as a null point exception. The Null Object Idiom (or Pattern, if you like) copes with this issue.

You can read more on this argument in chapter six of Head First Design Patterns where the Null Object Idiom (or Pattern) is introduced as an aside when discussing the Command Pattern.

Let's say we have a method that returns an object of a class derived from the interface Base or, in case no actual object could be generated, just a null. And let's say out client code should get a Base-derived object and then call a method on it. The usual code we write in this situation is something like this:
// ...
Base base = factory.create(/* ... */);
if(base != null)
    base.doSomething();
//...
The nuisance here is that we should pollute the code with checks against null, and the logical error deriving from forgetting it once somewhere is difficult to track down, since that the code is still working correctly. Almost always.

Often we can simply remove the use of checking against null, at the price of returning the instance of a fake class, when nothing sensible could be returned.
public interface Base {
    public void doSomething();
}

public class NullObject implements Base {
    public void doSomething() {}
}

public class Factory {
    public Base create(/* ... */) {
        switch /* ... */ {
        // ...
        default:
            return new NullObject();
        }
    }
}
In this way we don't need anymore the check against null:
// ...
Base base = factory.create(/* ... */);
base.doSomething();
//...
If we still need to know in the client code if we are working with a real object or the null one, we could always check its type through the instanceof operator.

Go to the full post

Singleton

One among the most popular pattern, the Singleton Pattern ensures a class could have just one instance, and provides a way to access it. Here you can see a preview of what is said on the matter in chapter five of Head First Design Patterns.

If the code you are dealing with is executed by just one thread, you could rely on a simple version of Singleton, that in Java looks something like that:
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if(instance == null)
            instance = new Singleton();

        return instance;
    }
}
Quite straightforward, but it could not work in a multithreading environment, since there is no synchronization on the code that actually create the resource. A simple patch would be this:
public static synchronized Singleton getInstance() {
    if(instance == null)
        instance = new Singleton();
    return instance;
}
The issue on this is that synchronization is expensive, and sometime we are not so happy to have to pay for it, when it is not strict necessity. We can move the creation of the instance in the static initializer, that is guaranteed by JVM to be thread safe:
public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

Cool, isn't it? The static initializer is called on the first attempt to access a Singleton method, and then what the getInstance() method has to do is just returning its instance.

Otherwise we could use the double-checked locking idiom, like showed here:
public class Singleton {
    private volatile static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if(instance == null) {
            synchronized(Singleton.class) {
                if(instance == null)
                    instance = new Singleton();
            }
        }
        return instance;
    }
}
The instance is volatile so each thead would ensure to check its actual value when using it. In getInstance() we enter a synchronized region only if we need it, so just if the instance is currently null. Once entered the critical region we have to check again the instance, to ensure it is still null.

Go to the full post

Factory Method

If our requirements for a factory are not too demanding, we could use the simple factory pattern we have seen in the previous post. But usually is better to think to the Factory Method Pattern. Here are a few hotes I have jotted down while reading the second part of chapter four of Head First Design Patterns, by Freeman, Freeman, Sierra, Bates. Get the book for more details.

Let's think the case where our application has to manage not a single pizza store but a chain of them, where each one should be able to create each pizza based not only on its own type but also on the store location.

TO do that, we'd better move the factory capability to an abstract method of the PizzaStore class, implementing it accordingly to the local requirements.

That will be now our class:
public abstract class PizzaStore {
    public Pizza orderPizza(String type) {
    Pizza = createPizza(type);

    pizza.prepare();
    // ...

    return pizza;
    }

    abstract Pizza createPizza(String type);
}
Any concrete pizza store now owns the factory methods that knows how to create its specific pizza. The recipe is the same for all the pizza stores, so it is kept in the orderPizza() method available in the base class, but the actual pizza is going to be generated based on to the local store requirements.

Generically speaking, the trick is to declare in the base class an abstract method that provides the signature that has to be respected by all the concrete classes for the factory method:
abstract Product factoryMethod(/*...*/);
So we can say that the Factory Method pattern is about defining an interface for creating a Product in a base class, and letting the derived classes to decide which actual concrete Product instantiate. The instantiation of the product is deferred to the subclass.

Go to the full post

Simple Factory

One of the main idea about modern Object Oriented Design is that we should tend to refer to interfaces instead of concrete classes. This leads the design to be as flexible as possible. But using the new operator drives us necessary in the opposite direction.

So, instead of using directly the new operator is often better to delegate the actual creation of an object to a specific functionality. This is showed by the Factory Pattern. In chapter four of
Head First Design Patterns
we are introduced to three different Factory Patterns.

In this post I'm about to talk about the first of them, a basic, stripped down, version aptly dubbed Simple Factory. It is so simple that it is often considered more a programming idiom than a pattern.

Let's ponder over this code, were a pizza is created:
Pizza order() {
   Pizza pizza = new Pizza();

   pizza.prepare();
   pizza.bake();
   pizza.cut();
   pizza.box();
   return pizza;
}
Aiming at some generalization, we could allow the user to create different types of pizza:
Pizza order(String type) {
   Pizza pizza;
   if(type.equals("cheese"))
      pizza = new PizzaCheese();
   else // ...

   // ...
   return pizza;
}
The code is getting messy. It looks natural to grab all the code related to the pizza creation and move it a specific place, that could be called anytime we want to generate a new pizza. And so that is our first factory:
public class SimplePizzaFactory {
   public Pizza create(String type) {
      Pizza pizza = null;

      if(type.equals("cheese"))
         pizza = new PizzaCheese();
      else // ...

      return pizza;
   }
}

We simply moved the code for generating pizzas in a dedicated class. The create() method could be static, and in this case we should not actually create an instance of the class for using it. But this bonus comes at the price of losing the chance of creating a derived class and so changing the method behavior.

Go to the full post

Decorator

If you read the third chapter of Head First Design Patterns you would understand where the stuff I writing here comes. Actually, I have written this post when I was reading that book, as a way to have even more fun.

The Decorator pattern is a way to attach extra responsibilities to an object dynamically. In this sense it could be seen as an alternative to subclassing for extending functionality.

The idea of this pattern is that we have Component, an abstract class that a ConcreteComponent should extends. We create a lateral hierarchy of decorators that are based on the Decorator abstract class that extends Component. Each decorator HAS-A Component, that is, the object that it improves. Any decorator IS-A Component, since it extends the Component through Decorator, but this is used only for type matching, to give the decorator the flexibility of being used as a Component, but we are not using the public inheritance to get the Component behavior.

As an example we can think to a way to manage a hierarchy of beverages, were each base beverage could be enhanced by a series of condiments.

The base class of our hierarchy is Beverage, and any concrete beverege would extends it, as an Espresso. The Condiment abstract class would extends Beverage and would be the base for any components that we could add to our beverages. We'll have, for instance a Milk condiment. So, to get a espresso with milk we'll create a Milk object passing it a Espresso object as parameter.

Let's see the code for that. Here is the base of the beverages hierarchy:
public abstract class Beverage {
   String description;

   public String getDescription() {
      return description;
   }

   public abstract double cost();
}
The class is abstract, it can't be instantiate directly. We need a concrete beverage to extend it, defining the description and the cost for the beverage. This is done here, for the espresso:
public class Espresso extends Beverage {
   public Espresso() {
      description = "Espresso";
   }

   public double cost() {
      return 1.99;
   }
}
The condiments are based on Decorator, that derives from Beverage itself:
public abstract class Decorator extends Beverage {
   protected Beverage beverage;

   public Decorator(Beverage beverage) {
      this.beverage = beverage;
   }

   @Override
   public abstract String getDescription();
}

The decorator has a reference to the beverage it modifies, that is set by the constructor. The getDescription() method overrides the Beverage one, and has to be overridden by the concrete decorators. Let's see a couple of condiments:
public class Mocha extends Decorator {
   public Mocha(Beverage beverage) {
      super(beverage);
   }

   @Override
   public String getDescription() {
      return beverage.getDescription() + ", Mocha";
   }

   @Override
   public double cost() {
      return beverage.cost() + 0.20;
   }
}

// ...

public class Whip extends Decorator {
   public Whip(Beverage beverage) {
      super(beverage);
   }

   @Override
   public String getDescription() {
      return beverage.getDescription() + ", Whip";
   }

   @Override
   public double cost() {
      return beverage.cost() + 0.10;
   }
}
The original Beverage methods are overridden to refer to the Beverage owned as data member from the decorator.

Here is the code that create a plain espresso and a fancy espresso double mocha and whip:
Beverage b = new Espresso();
System.out.println(b.getDescription() + " €" + b.cost());

Beverage b2 = new Whip(new Mocha(new Mocha(new Espresso())));
System.out.println(b2.getDescription() + " €" + b2.cost());

Go to the full post

Observer

This post on the observer pattern is based on chapter two of HFDP - Head First Design Patterns, quite a fun and interesting O'Really book.

The observer pattern defines a one to many relation between objects. Among the different names used to identify the actors in game the most popular are subject/dependent object and publisher/subscriber. The basic idea of the relation is that when the state of the subject change, the observers are notified.

The subject interface should include three methods. Two are required to allow an observer to register and to remove its registration, the third one is used to notify the observers a change in the subject status. The observer interface should include just a method used by the subject to notify its changes.

The Observer pattern allows us to set a loose coupling between subject and observers. This is good, because helps us to get a flexible design.

As an example of the observer pattern, it is presented a toy application that shows data coming from a hardware appliance (a Weather Station) in a few displays.

Looks natural thinking to the Weather Station as subject of the observer pattern and the displays as observers.

Here is the interfaces that are at the base of this architecture:
public interface Subject {
    public void register(Observer o);
    public void remove(Observer o);
    public void notifyObservers();
}

public interface Observer {
    public void update(float temperature, float humidity, float pressure);
}

public interface Display {
    public void display();
}

The Display interface is going to be used by the observers, to expose the common behaviour that characterize them as displaying unit.

Here is the implementation of the Weather Station:
import java.util.ArrayList;
import java.util.Iterator;

public class WeatherStation implements Subject {
    private ArrayList<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherStation() {
        observers = new ArrayList();
    }

    public void register(Observer o) {
        observers.add(o);
    }

    public void remove(Observer o) {
        observers.remove(o);
    }

    public void notifyObservers() {
        Iterator<Observer> it = observers.iterator();
        while(it.hasNext())
            it.next().update(temperature, humidity, pressure);
    }

    public void set(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;

        notifyObservers();
    }
}

The core of the class is probably its notifyObservers() method that iterates on all the registered observers to call update() on each of them.

Here is a possible implementation for a displaying class:
public class DisplaySimple implements Observer, Display {
    Subject weatherStation;
    private float temperature;

    public DisplaySimple(Subject weatherStation) {
        this.weatherStation = weatherStation;
        weatherStation.register(this);
    }

    public void update(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        display();
    }

    public void display() {
        System.out.println("DisplaySimple says temperature is " + temperature);
    }
}
The reference to the Subject object is kept thinking ahead for a next version of this class where would be provided a way to unregister to the subject of the observation directly from the subscriber class.

A few line of code for testing the system (assuming another displaying class - DisplayFull - is provided):
WeatherStation ws = new WeatherStation();
DisplaySimple ds = new DisplaySimple(ws);
DisplayFull df = new DisplayFull(ws);

System.out.println("First measure setting");
ws.set(12, 23, 44);

ws.remove(df);

System.out.println("Second measure setting");
ws.set(123, 233, 544);

Go to the full post

Strategy

This discussion on the strategy pattern is based on what is written in chapter one of HFDP - Head First Design Patterns, where the description of this pattern is used to give the reader an introduction to the Design Patterns.

Our action starts when we already have a hierarchy of classes representing different kind of ducks. On top we have Duck, a class implementing the plain vanilla duck, that is extended to change some specific aspects of more detailed ducks. We could have, for instance, MallardDuck and RedheadDuck, overriding the required methods to get some different details.

We face a change, we want add a new functionality to the ducks, to let them fly. A natural solution would be change the base class of the duck hierarchy, adding a fly() method to Duck. But not always this is a good idea. In our case, our duck hierarchy includes also peculiar ducks, as RubberDuck, that is not a duck in the living bird sense of the term. For what we care here, this particular duck has no use of fly(). But adding a fly() method to Duck implies that now even our rubber ducks could fly.

A quick solution to this issue would be overriding the fly() method in each class derived from Duck that does have a different behavior. This is OK for a small hierarchy, but in our case we have a huge number of different duck classes, and we are expecting a lot of changes in the classes structure in the future. In such a case, this approach could lead to a maintenance nightmare.

An alternative solution would be to take out from the Duck class definition all the methods that could be present or not in the derived ducks and make them available through interfaces. So, MallardDuck would extends Duck and implement the interfaces Flyable and Quackable (for the methods fly() and quack()), RubberDuck would implement just Quackable, and so on. But this solution would be even more error prone and hard to mantain that the original one.

There is no Multiple Inheritance (MI) in Java, so even if we wanted we can't use it here. Using MI we could have designed the ducks in a way that they compose in their behavior a part that is common to all the ducks, and we expect not to vary (at least not frequently) in the course of the development, and other elements that we think are more subject to change.

But here it would be more useful to put in the superclass Duck the information relative to the fact that we have a reference to external classes that provide us part of the functionality for the actual duck. The idea is to have a Duck that has as protected members a number of interfaces, each of them for a specific behavior that we want to manage in our actual duck.

Any of this interface would be the root of a hierarchy of classes that would provide the actual functionality for ducks. So, for instance, the interface FlyBehaviour will provide a method fly() that will be implemented in the classes FlyWithWings and FlyNoWay. Any real class derived from Duck should take care of setting the interfaces defined in the Duck superclass using one of this classes.

We can see it in this way: the Duck class delegates a few of its behaviors (the ones we want to keep more easy to change) to external classes. It is a task of the classes derived from Duck to specify in their constructor what the real behavior should be.

Let's sketch how this should work. About flying, the class Duck should do something like that:
public abstract class Duck { // 1
    protected FlyBehaviour fly;
    // ...

    public void doFly() {
        fly.doIt(); // 2
    }
    // ...
}
1. it doesn't make any sense to instantiate a Duck, so we explicitly mark the class as abstract
2. the implementation of the flying is simply delegated to the FlyBehaviour hierarchy

The FlyBehaviour hierarchy should be like this:
public interface FlyBehaviour {
    void doIt();
}

public class FlyWithWings implements FlyBehaviour {
    public void doIt() {
        System.out.println("flying with wings");
    }
}

public class FlyNoWay implements FlyBehaviour {
    public void doIt() {
        System.out.println("not flying");
    }
}
Given that, we should define a real duck in this way:
public class DuckMallard extends Duck {
    public DuckMallard() {
        fly = new FlyWithWings();
    }
}
And we would use it like that:
Duck d = new DuckMallard();
d.doFly();
But there is more. Having implemented our Duck hierarchy in this way it is easy to change the behavior of a duck at execution time. It is enough to provide a setFlyingBehaviour() method that would set the FlyBehaviour member accordingly with our current requirement.

So, extracting the changing behaviors from the Duck hierarchy and putting them in their specific hierarchies, and shifting that relation in the field of composition has the result that we get a lot of more flexibility.

Go to the full post