Showing posts with label Pattern. Show all posts
Showing posts with label Pattern. Show all posts

Module pattern template

My current project makes use of different technologies, for presentation we rely on a mix of Java EE and JavaScript. We try not to mess around too much with the latter, and we strive to keep that code as readable as possible. For this reason we break the JavaScript code in modules that, ideally, are all written following the same template, so that it is easy for anyone in the team to put his hands on any piece of code available.

Here is an example of how we typically write a module.

As you will see, we use the well known module pattern, with a few specific variations:
var APP = APP || {}; // 1

APP.Module = (function(app, global, $) { // 2
  "use strict"; // 3

  var FIRM_NAME = 'XYZ'; // 4

  function Factory(options) { // 5
    var that = this; // 6

    if(!(this instanceof Factory)) { // 7
      return new Factory();
    }

    this.options = $.extend({ name: null }, options); // 8

    function _checkName() { // 9
      if(that.options.name) {
        console.log('In a private function, use that instead of this');
        return true;
      }
      else {
        return false;
      }
    }

    this.getName = function getName() { // 10
      return FIRM_NAME + (_checkName() ? ': ' + this.options.name : '');
    }

    return this; // 11
  }

  Factory.aFunction = function() { // 12
    if(this == Factory) {
      console.log('A static function has no access to instance variables');
    }
    else { // called by sayHello, see below
      console.log('Instance', this.options.name);
    }
  }

  Factory.prototype.sayHello = Factory.aFunction; // 13

  return Factory; // 14
}(APP, this, jQuery)); // 15
1. First thing, I define a namespace for all the modules. Or better, if APP is already defined, I use it as it is in the following code. Only if no APP is already available a create it from scratch.
2. In APP, I create a module named Module (usually it is a good idea choosing a better name). As you see, it is nothing more that an immediate function that receives in input three parameters, see the module last line (point 15.) to find out what they are.
3. The JavaScript code used is "strict".
4. This is a private variable (ideally, a constant) available to all the Module instances.
5. The Module's constructor. It accepts in input a variable used to set the internal object properties. In this case "options" contains just a single value, so it is an overkill not to use it. But usually options contains a large number of properties.
6. The infamous "this is that" pattern. Follow the link for more details.
7. Another well known JavaScript pattern. The constructor could be called improperly, with this check we avoid any unpleasant surprise.
8. We use jQuery, so to extends the "options" object passed to the constructor we use the jQuery .extend() function. Same functionality is provided by other frameworks, and it could also implemented with no special trouble by hands. The idea is that we want to ensure that our local "options" contains at least a property named "name". If the passed "options" has it, we will keep it, otherwise a new, empty one (or better, null), is created.
9. A private function. No one could access it outside its scope. Notice that inside it we have to use "that" to access the constructor "this".
10. A public function. It could be called from outside, and it has full access to the constructor and module properties.
11. As almost any constructor, at the end of its job it returns "this".
12. Sometimes it is useful to have a "static" (in the C++/Java sense) method in a module. Here is how we can emulate it. We can even use a trick (see 13.) to adapt this method so that it could also be called as a non-static function.
13. Here is the trick. We create a property in the Factory prototype, and we assign to it the static function. Neat.
14. Finally, the immediate function calls the constructor, so that the object is created.
15. We call the immediate function passing to it APP (the module's namespace), the current "this" (at this point it should be the global one), and jQuery (since we use it - you could pass your preferred framework instead, obviously. Or you could even pass many ones).

Here is a test usage for the above defined module:
var m1 = new APP.Module({name: 'John Smith'}); // 1
console.log(m1.getName());

var m2 = new APP.Module(); // 2
console.log(m2.getName());

APP.Module.aFunction(); // 3
console.log("Can't call a private function from outside:", m1._checkName === undefined);
console.log("Can't call an instance function from static context:", APP.Module.sayHello === undefined);
console.log("Can't call a static function from an object:", m1.aFunction === undefined);
m1.sayHello(); // 4
1. An object m1 is created, passing a name to the module.
2. Here we create an "anonymous" module, no name it is passed.
3. The static function is called on the module itself, it doesn't requires an actual instance.
4. But through that clever trick showed above on (13.) we can call the static function through an alias.

Go to the full post

Patterns working together

Chapter twelve of Head First Design Patterns is a sort of style exercise where lot of pattern are made working together. This is not what usually happens in real life, at least not at such extent, but it is interesting to check it out. I'd say that is better to read the book than this post, but it could give you a pale idea of what you could find there.

We have to write a duck simulator that manages ducks and anything that could sort of quacking. So, that means we are about to use the Adapter Patter, that helps us to adapt a sort-of-quacker (a goose) to react like a duck.

Then we want to add to the ducks a way to keep track of any time they quack, without modifying the duck classes. We'll use the Decorator Pattern for this.

The usage of decorator suggests us to create our ducks using the Abstract Factory Pattern, to avoid the risk of forgetting decorating a duck when creating it.

To keep simpler the management of our quacking animals we'll use the Composite Pattern, that helps us managing a flock of them as it would be a single quackable entity; besides we'll use the Iterator Pattern to go through all the elements in the composite.

Finally, we are about to use the Observer Pattern, to let a scientist (better known as a quackologist) to be notified any time a quackable animal quacks.

Let's start from the bottom. Our quacking being should be observable, that means it should implement an interface providing a way to the observer to register on it. And, simmetrically, we provide an interface that the observer has to implement, to be recognized by the observed entity and take an appropriate action when required:
public interface ObservableQuack {
    void register(Observer observer);
    void notifyObserver();
}

public interface Observer {
    void update(ObservableQuack duck);
}
We keep the class for the scientist as simple as possible:
public class Quackologist implements Observer {
    public void update(ObservableQuack duck) {
        System.out.println("Observed " + duck + " quacking.");
    }
}
It just puts string to the output console to acknowledge the duck quacking observation.

Our quacking friends implement a quackable interface, that would ask them to implement a quacking method, and all the methods required to be observable:
public interface Quackable extends ObservableQuack {
    public void quack();
}
Besides, we create an abstract class that would be the base class for each observable class, providing the standard implementation for the methods defined in the interface. That would avoid us to replicate the same code in many classes:
import java.util.ArrayList;

public abstract class Observable implements ObservableQuack {
    private ArrayList<Observer> observers = new ArrayList<Observer>();

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

    public void notifyObserver() {
        for(Observer o: observers)
            o.update(this);
    }
}
So, each duck instantiates a class that extends this Observable class and implement the Quackable interface:
public class DuckMallard extends Observable implements Quackable {
    public void quack() {
        System.out.println("Quack!");
        notifyObserver();
    }
}

// ...

public class DuckCall extends Observable implements Quackable {
    public void quack() {
        System.out.println("Kwak!");
        notifyObserver();
    }
}

// ...

public class DuckReadhead extends Observable implements Quackable {
    public void quack() {
        System.out.println("Quack!");
        notifyObserver();
    }
}

// ...

public class DuckRubber extends Observable implements Quackable {
    public void quack() {
        System.out.println("Squeak!");
        notifyObserver();
    }
}
We are about using the Duck classes wrapped in this decorator:
public class QuackCounter implements Quackable {
    Quackable duck;
    static int counter;

    public QuackCounter(Quackable duck) {
        this.duck = duck;
    }

    public void quack() {
        duck.quack();
        ++counter;
    }

    public static int getCounter() {
        return counter;
    }

    public void register(Observer observer) {
        duck.register(observer);
    }

    public void notifyObserver() {
        duck.notifyObserver();
    }
}
The QuackCounter redirects the calls it receives to the owned instance, we just add an increase in the counter any time we call the quack() method. To help the user not forgetting about using it, we make available a factory that the client would use to generate the ducks:
public abstract class AbstractDuckFactory {
    public abstract Quackable createDuckCall();
    public abstract Quackable createDuckMallard();
    public abstract Quackable createDuckReadhead();
    public abstract Quackable createDuckRubber();
}

// ...

public class CountingDuckFactory extends AbstractDuckFactory {
    @Override
    public Quackable createDuckCall() {
        return new QuackCounter(new DuckCall());
    }

    @Override
    public Quackable createDuckMallard() {
        return new QuackCounter(new DuckMallard());
    }

    @Override
    public Quackable createDuckReadhead() {
        return new QuackCounter(new DuckReadhead());
    }

    @Override
    public Quackable createDuckRubber() {
        return new QuackCounter(new DuckRubber());
    }
}
But what about our goose?
public class Goose {
    public void honk() {
        System.out.println("Honk!");
    }
}
We provide an adapter so that we could use it as it would be a duck:
public class GooseAdapter extends Observable implements Quackable {
    private Goose goose;

    public GooseAdapter(Goose goose) {
        this.goose = goose;
    }

    public void quack() {
        goose.honk();
        notifyObserver();
    }
}
And here is an aggregate, that help us to manage a flock of quackables in an easy way:
import java.util.ArrayList;

public class Flock extends Observable implements Quackable {
    private ArrayList<Quackable> flock = new ArrayList<Quackable>();

    public void add(Quackable element) {
        flock.add(element);
    }

    public void quack() {
        for(Quackable q: flock)
            q.quack();
    }

    @Override
    public void register(Observer observer) {
        for(Quackable q: flock)
            q.register(observer);
    }

    @Override
    public void notifyObserver() {
        for(Quackable q: flock)
            q.notifyObserver();
    }
}
Basically any method just delegates the behaviour to the elements of the flock.

And here is a little tester for our application:
public class Simulator {
    public static void main(String[] args) {
        AbstractDuckFactory factory = new CountingDuckFactory();
        new Simulator().simulate(factory);
    }

    private void simulate(AbstractDuckFactory factory) {
        System.out.println("Duck Simulator");

        Flock flock = new Flock();
        flock.add(factory.createDuckMallard());
        flock.add(factory.createDuckReadhead());
        flock.add(factory.createDuckCall());
        flock.add(factory.createDuckRubber());
        flock.add(new GooseAdapter(new Goose()));

        Quackologist quack = new Quackologist();
        flock.register(quack);

        simulate(flock);

        System.out.println("Number of quacks: " + QuackCounter.getCounter());
    }

    private void simulate(Quackable duck) {
        duck.quack();
    }
}

Go to the full post

Protection Proxy by dynamic proxy

The Protection variation of the Proxy Pattern is meant to provide an extra level on flexibility, so that part of the interface of a class could be accessed by the user.

To show an usage of this pattern, we'll use the proxy support that Java makes available through the reflection package. It is called a dynamic proxy, Java creates it on the fly, when we need it. Since the proxy creation is done by Java directly, we should have a way of specifying the behavior we want to implements. This is done by making available to the Java proxy an object that instantiates a class derived from the interface InvocationHandler.

We want to implement a matchmaking system where a profile is available for each user. The issue is that there is one setter a user can't call for its own profile (the one to set how much a user likes that profile - you can't do that on your own profile!), but just on other people profile.

So, if this is the interface for the profile:
public interface PersonBean {
    String getName();
    String getGender();
    String getInterests();
    int getRating();

    void setName(String name);
    void setGender(String gender);
    void setInterests(String interests);
    void setRating(int rating);
}

And this is a concrete implementation:
public class PersonBeanImpl implements PersonBean {
    private String name;
    private String gender;
    private String interests;
    private int rating;
    private int count;

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

    public String getInterests() {
        return interests;
    }

    public int getRating() {
        if(count == 0)
            return 0;
        return rating / count;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setInterests(String interests) {
        this.interests = interests;
    }

    public void setRating(int rating) {
        this.rating += rating;
        ++count;
    }
}
We want to make available a proxy to protect the access to the setRating() method.

To do that, we create two class implementing InvocationHandler, one to be used from a user when it wants to access its own profile, and the other when it wants to access someone else's profile:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class IHOwner implements InvocationHandler {
    PersonBean person;

    public IHOwner(PersonBean person) {
        this.person = person;
    }

    public Object invoke(Object proxy, Method method, Object[] args)
    throws IllegalAccessException {
        try {
            if(method.getName().startsWith("get"))
                return method.invoke(person, args);
            if(method.getName().equals("setRating"))
                throw new IllegalAccessException();
            if(method.getName().startsWith("set"))
                return method.invoke(person, args);
        } catch(InvocationTargetException ite) {
            ite.printStackTrace();
        }
        return null;
    }
}

// ...
public class IHNonOwner implements InvocationHandler {
    PersonBean person;

    public IHNonOwner(PersonBean person) {
        this.person = person;
    }

    public Object invoke(Object proxy, Method method, Object[] args)
    throws IllegalAccessException {
        try {
            if(method.getName().startsWith("get"))
                return method.invoke(person, args);
            if(method.getName().equals("setRating"))
                return method.invoke(person, args);
            if(method.getName().startsWith("set"))
                throw new IllegalAccessException();
        } catch(InvocationTargetException ite) {
            ite.printStackTrace();
        }
        return null;
    }
}

Now, the job of creating the proxy is done by Java. We "just" have to call this piece of code:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public static PersonBean getProxy(PersonBean person, InvocationHandler ih) {
    return (PersonBean)Proxy.newProxyInstance(
        person.getClass().getClassLoader(),
        person.getClass().getInterfaces(), ih);
}

We call the factory method newProxyInstance() in the class Proxy, passing it the loader and the interfaces to the class the proxy has to stand for, and the required invocation handler that would tell the proxy how to behave.

Here is a little test client that should help understanding how to use this proxy:
PersonBean p = new PersonBeanImpl();
PersonBean proxy = PersonBeanProxy.getProxy(p, new IHOwner(p)); // 1
try {
    proxy.setRating(10);
} catch (Exception e) {
    System.out.println("Can't set rating.");
}

proxy = PersonBeanProxy.getProxy(p, new IHNonOwner(p)); // 2
try {
    proxy.setInterests("Snorkeling");
} catch (Exception e) {
    System.out.println("Can't set interests.");
}
1. We want the proxy acting as an owner, since we passed an IHOwner instance to the creator. That means it is not possible to call setRating() on it. If we try to call this method, we'll have an exception.
2. Now the proxy is acting as a non owner. So we can't call any setter that is not setRating(). Therefore, the call to setInterests() would result in an exception.

I have written this post while reading chapter eleven of Head First Design Patterns, that is all about proxy.

Go to the full post

Virtual Proxy

In the previous post I have summarized the formal description for the Proxy Pattern, as described in HFDP - Head First Design Patterns. Now it is time to talk about Virtual Proxy, a pattern that is close to the Remote Proxy, referring to a resource that is not local.

The Virtual Proxy is typically used when the RealSubject is expensive to create. So, we initially don't create the RealSubject, but we give the user just a cheap surrogate; in the meanwhile the proxy start working to make available the RealSubject and then it would delegate the user requests to it.

As an example of virtual proxy, we can think of an application that displays images that have to be fetched on the internet. Since the connection could be slow, it makes sense to implement the viewer as a virtual proxy, displaying to the user just a label until the real thing is locally available.

I rearranged a bit the code to let us put some waiting inside, and using a lot of faking, instead of real pictures. As a bonus, I cleaned up the code throwing in the State pattern (as it is actually suggested by the HFDP's authors).

Our fake image is an object of a class implementing this interface:
public interface FakeImage {
    void paint();
    int size();
}
We assume that a real FakeImage, whatever it would be, implements too this interface, but here we see just the virtual proxy, that is designed to assume two states: Faking, until the FakeImage is loaded, and then Available.

Here is the states:
public interface State extends FakeImage {} // 1

// ...

public class StateAvailable implements State { // 2
    FakeImageProxy proxy;

    public StateAvailable(FakeImageProxy proxy) {
        this.proxy = proxy;
    }

    public void paint() {
        System.out.println(proxy.getFakeImage());
    }

    public int size() {
        return proxy.getFakeImage().length();
    }
}

// ...

public class StateFaking implements State {
    private Thread tLoader;
    private boolean retrieving;
    private FakeImageProxy proxy;

    public StateFaking(FakeImageProxy proxy) {
        this.proxy = proxy;
    }

    public void paint() { // 3
        System.out.println("please wait ...");
        if (!retrieving) {
            retrieving = true;
            tLoader = new Thread(new Runnable() {
                public void run() {
                    synchronized (this) {
                        try { wait(1000); } catch (Exception e) {}
                    }
                    proxy.setFakeImage("A string pretending to be an image");
                    proxy.imageLoaded(); // 4
                }
            });

            tLoader.start();
        }
    }

    public int size() {
        return 0;
    }
}
1. We actually could avoid to use a specific interface for the State, since it is just a synonym for FakeImage. But I reckon it makes the code clearer this way, and I'd say it is worthy.
2. When we are in the Available state, there is not much to do.
3. When in Fake, on the other side, we see what really is the pattern about. The paint() method provides a surrogate, and takes care of making available the real thing.
4. When the (fake) image is available, we signal the proxy we should change state accordingly.

The code for the proxy, thanks to the State Pattern, is quite simple:
public class FakeImageProxy implements FakeImage {
    private String fakeImage;

    private State faking = new StateFaking(this);
    private State available = new StateAvailable(this);
    private State current = faking;

    public void paint() {
        current.paint();
    }

    public int size() {
        return current.size();
    }

    void setFakeImage(String fakeImage) {
        this.fakeImage = fakeImage;
    }

    void imageLoaded() {
        current = available;
    }

    public String getFakeImage() {
        return fakeImage;
    }
}
Here is a short tester:
FakeImage fk = new FakeImageProxy();
while(fk.size() == 0) {
    synchronized (fk) {
        fk.paint();
        try { fk.wait(200); } catch(Exception ex) {ex.printStackTrace();}
    }
}
fk.paint();

Go to the full post

Proxy

The Proxy Pattern provides a surrogate/placeholder for another object with the intent of providing an extra layer of access control.

In Object-Oriented languages, the access control to an object is normally achieved exposing a different interface to the client accordingly to its privilege. In Java we have private, protected, package, an public modifiers that could be used for this purpose.

Sometimes this is not enough. We want to rule the access to our object in a way that is not achievable through the standard OO schema.

In the case of the remote proxy, the point is different. There we just want to hide to the user object the complexity of accessing a remote object, exposing locally the same interface of the object it needs.

In any case, the idea of a proxy is that we have an interface (named Subject in this context) that is implemented by both the RealSubject (the object's class the client wants to access) and Proxy.

Since the actual interface is the same, and since we should strive to program to interfaces, from the point of view of the client there is little or almost no difference between using the RealSubject or the Proxy. So we can safely hide in the proxy all the functionality we are required to provide to the client.

Chapter eleven of Head First Design Patterns, is about proxy. I suggest you to get the book to have more information on the matter.

Go to the full post

Remote Proxy - RMI

Sometimes is useful to use an object as a shield to the access to the real thing, and that is where the Proxy Pattern comes in handy. A typical example is the Remote Proxy, where the proxy is meant to be a local representative to a remote object.

The access to objects on a different JVM could be performed using RMI, Remote Method Invocation. In the RMI context we say that we have an RMI stub on the client JVM that acts as a proxy to a local object. The stub would gain access to its related RMI skeleton on the target JVM, that would resolve the original call to the required object.

An example should help us to understand better what we are talking about.

The connection between the stub and skeleton is provided by an interface that would declare the available methods. Let's call it MyRemote:
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface MyRemote extends Remote { // 1
    public String sayHello(String name) throws RemoteException; // 2
}
1. The Remote interface is just a marker, doesn't have any method in it. To be used by RMI an interface has to extend it.
2. Any method in a remote interface is unsafe, since anything could happen in a network. So a requisite for each method in this context is that is should be declare throwing a RemoteException. The input/output parameters in a method should be primitive or Serializable. String is serializable, so it is OK.

The UnicastRemoteObject class helps us to have a simpler job implementing the remote service:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
    public MyRemoteImpl() throws RemoteException {}

    public String sayHello(String name) throws RemoteException {
        return "Hi " + name + ".";
    }

    public static void main(String[] args) {
        try {
            MyRemote service = new MyRemoteImpl();
            Naming.rebind("RemoteHello", service);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
We have include in the class the bootstrap code to lunch the service. Basically it just register our class in the RMI registry.

We can almost forget about stub and skeleton, since they are managed under the hood of this implementation, we just have to run rmic and let it do the dirty job:
rmic my.package.MyRemoteImpl
Well, "my.package." should be replaced with the actual package name where the class is placed. And rmic should have access to our class hierarchy.

Now we can launch the RMI registry, that would sit and wait for clients wanting to connect to our service:
rmiregistry
But before anyone could actually access the service, it should be in execution. So we start it:
java [-cp ...] my.package.MyRemoteImpl
So, that's it for the server.

The client is even simpler:
import java.rmi.Naming;

public class MyRemoteClient {
    static private final String url = "rmi://localhost/RemoteHello"; // 1
        public void go(String name) {
        try {
            MyRemote svc = (MyRemote) Naming.lookup(url); // 2
            System.out.println(svc.sayHello(name)); // 3
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}
1. OK, we actually have both client and server on the same machine, localhost. But the only thing that we have to change, in case of a real remote method invocation, is the URL that makes us available the service.
2. We need the interface MyRemote available here. There are cooler ways to do that, but in this implementation we have just copied the source file from the service project to the client one.
3. Here is where the magic happens. We are actually working with a stub provided by RMI, but we have the impression of working with the real thing.

In the application main we create an instance of the client and then here we go:
MyRemoteClient rc = new MyRemoteClient();
rc.go("Tom");

Chapter eleven of HFDP - Head First Design Patterns is about proxy, and there you can find also a quick introduction to RMI.

Go to the full post

State

The State Pattern allows an object to alter its behaviour when its internal state changes. From the object user's point of view, it looks like the object changes the class from which it is instantiated. And, given that we could use composition this is true, in a way: we expose the behavior of a different class, accordingly to the state that we want to show.

The class that could have a number of different states is usually called Context. Any requests that is made on Context is delegated to the currently active state of the Context itself. Any concrete state of the Context is derived from a common interface, here name State, that defines all the method required by the Context. Since all the concrete state implements it, they are all interchangeable.

You can see that the class diagram for State Pattern is the same of the Strategy Pattern one. The difference is in their intent. In the State Pattern the behavior is delegated form the Context to the current State, and this is seen as an internal detail of the Context class, so usually the client doesn't know much about it. It could be thought as an alternative of putting a lot of conditional statements in the Context, using the different concrete states as an encapsulation of its changing behavior.

On the other side, with Strategy is usually the client that specify the actual state of the configurable object, so we can think this pattern as a flexible alternative to subclassing. If all this results a bit unclear, I would suggest you to get HFDP - Head First Design Patterns a fine and fun book on patterns implemented in Java.

The example that should help us in better understanding the use of this pattern is based on the implementation of a software for the management of a gumball machine.

The user puts a coin in it, turns a crank, and he expects to get back a gumball. It looks like a simple mechanism, but actually there are a few subtleties that have to be checked carefully. The gumball machine should react in a different way to an action from the user accordingly to its internal status (the number of gumballs currently available) and the history of the previous actions applied to the machine. Actually, our gumball machine is a simple finite state machine.

Once we have seen that, it comes quite natural to implement the gumball machine using the State Pattern. Let's think about the states our machine could have:
  • No Coin: this is the "normal" state. The machine has gumballs ready for selling, and it is waiting for clients.
  • Has Coin: we reach this state when the user puts a coin in the machine, causing the transition to here from the No Coin state.
  • Sold: we arrive here from Has Coin, when the user turns the crank. When we enter this state, the machine should internally cause a gumball to be delivered to the user. After that we should go to the No Coin state or, if no gumball is available anymore we should go to the Sold Out state.
  • Sold Out: no gumball is available. The only operation that makes sense in this state is the refill of the machine, that sends us to the No Coin status.
Besides, we create another state, Winner, that is a variation of Sold where two gumballs are delivered to the user, if available.

The transition among the states is ruled by a few operations:
  • The user inserts a coin: it makes sense only if we are in the No Coin state, and in this case it let us move to the Has Coin state.
  • The user asks his coin back: if we are in the Has Coin state, moves us back to the No Coin state. Otherwise it has no result.
  • The user turns the crank: only if we are in Has Coin we go to the Sold state, ready to deliver the gumball to the user.
  • The machine dispenses a gumball: the gumball machine, when the Sold state is reached, calls this operation.
Let's see a way to implement this bunch of states. First thing we create an abstract class with the default implementation for each state:
abstract class State { // 1
    void insertCoin() {
        System.out.println("Can't insert a coin now");
    }

    void ejectCoin() {
        System.out.println("Can't eject a coin now");
    }

    boolean turnCrank() { // 2
        System.out.println("No use in turning the crank now");
        return false;
    }

    void dispense() {
        System.out.println("Can't dispense a gum now");
    }
}
1. The class and the methods have package visibility, since these are internal details not available to the user.
2. The turnCrank() method returns a boolean, so that the machine would know when it makes sense to call dispense() - that is, only when the turning of the crank succeeded.

The machine is ready to dispense gumballs, we just wait for the user to put his coin in it, we are in the NoCoin state:
class StateNoCoin extends State {
    private GumballMachine machine;

    StateNoCoin(GumballMachine machine) {
        this.machine = machine;
    }

    @Override
    void insertCoin() {
        System.out.println("Coin inserted");
        machine.setState(machine.getStateHasCoin());
    }
}
When the coin is in the machine, the user could change his mind, asking for his coin back, or give us the OK for the gumball. We should randomly decide if we give him one or two gums for his money:
import java.util.Random;

class StateHasCoin extends State {
    private GumballMachine machine;
    private Random generator = new Random(System.currentTimeMillis());
    private static final int LUCKY = 10;

    StateHasCoin(GumballMachine machine) {
        this.machine = machine;
    }

    @Override
    void ejectCoin() { // 1
        System.out.println("Get your coin back");
        machine.setState(machine.getStateNoCoin());
    }

    @Override
    boolean turnCrank() { // 2
        System.out.println("Turning ...");
        if(generator.nextInt(LUCKY) == 0)
            machine.setState(machine.getStateWinner());
        else
            machine.setState(machine.getStateSold());

        // turning has success
        return true;
    }
}
1. The user has changed his mind, we get back to the No Coin status.
2. The turn of the crank could send us, randomly, to the Sold or to the Winner state. In any case we return true to the caller, to signal it that it makes sense now to call the delivery method.

The user has turned the crank, the gumball is sold, we had ho luck so we are about to get just one gumball:
class StateSold extends State {
    protected GumballMachine machine; // 1

    StateSold(GumballMachine machine) {
        this.machine = machine;
    }

    @Override
    void dispense() { // 2
        machine.releaseBall();
        if(machine.getGumballsNumber() == 0) {
            System.out.println("This was the last gumball!");
            machine.setState(machine.getStateSoldOut());
        } else {
            machine.setState(machine.getStateNoCoin());
        }
    }
}
1. We are going to extend StateSold for defining the Winner state, so the machine reference is protected, for being visible to the derived class, too.
2. After the machine releases the gumball, we change the state to No Coin, ready for another run, or to Sold Out, if no more gumballs are available.

We have been lucky, we are about to get two gumballs:
class StateWinner extends StateSold { // 1
    StateWinner(GumballMachine machine) {
        super(machine);
    }

    @Override
    void dispense() {
        machine.releaseBall();
        if(machine.getGumballsNumber() == 0) { // 2
            System.out.println("Damn, that was the last gumball");
            machine.setState(machine.getStateSoldOut());
        } else {
            System.out.println("Lucky guy! You get two gums for a coin.");
            super.dispense(); // 3
        }
    }
}
1. The Winner state is just a variation of the Sold state, so we design the StateWinner class as an StateSold extension.
2. After giving the user the gumball he paid for, we check if we actually have another one available. If not we change the state to Sold Out. The user won a second ball, but we can't give it to him.
3. To deliver the free gum the lucky user has won, we fallback to the superclass implementation for this method.

Out of gum, we can't do anything, until we get a refill:
class StateSoldOut extends State {
    @Override
    public void insertCoin() {
        System.out.println("Sorry: sold out - get back your coin"); // 1
    }
}
1. If a user put his money in the machine we tell him to get it back.

Our gumball machine starts in the No Coin (or in the Sold Out) state and change to different states accordingly to the action ruled by the class public interface. Notice that the change of state is done by the State-derived classes:
public class GumballMachine {
    private State stateNoCoin = new StateNoCoin(this);
    private State stateHasCoin = new StateHasCoin(this);
    private State stateSoldOut = new StateSoldOut();
    private State stateSold = new StateSold(this);
    private State stateWinner = new StateWinner(this);

    private int gumballs;
    private State current;

    public GumballMachine(int gumballs) {
        this.gumballs = gumballs;
        current = (gumballs > 0) ? stateNoCoin : stateSoldOut;
    }

    public int getGumballsNumber() {
        return gumballs;
    }

    State getStateHasCoin() {
        return stateHasCoin;
    }

    State getStateNoCoin() {
        return stateNoCoin;
    }

    State getStateSold() {
        return stateSold;
    }

    State getStateSoldOut() {
        return stateSoldOut;
    }

    State getStateWinner() {
        return stateWinner;
    }

    void setState(State state) {
        this.current = state;
    }

    void releaseBall() {
        System.out.println("You can get your gumball.");
        if(gumballs > 0)
        --gumballs;
    }

    public void insertCoin() {
        current.insertCoin();
    }

    public void ejectCoin() {
        current.ejectCoin();
    }

    public void turnCrank() {
        if(current.turnCrank())
            current.dispense();
    }

    public void refill(int moreGumballs) {
        System.out.println("Adding " + moreGumballs + " gumballs.");
        gumballs += moreGumballs;
        current = (gumballs > 0) ? stateNoCoin : stateSoldOut;
    }

    @Override
    public String toString() {
        return current.toString() + " [" + gumballs + ']';
    }
}
Here is a few lines to do a smoke test of the gumball machine:
GumballMachine gm = new GumballMachine(5);
System.out.println(gm);

gm.insertCoin();
gm.turnCrank();
System.out.println(gm);

gm.insertCoin(); // just to mess up a bit
while(gm.getGumballsNumber() > 0) {
    gm.insertCoin();
    gm.turnCrank();
}

System.out.println(gm);
gm.insertCoin();
gm.turnCrank();
System.out.println(gm);

gm.refill(2);
System.out.println(gm);
while(gm.getGumballsNumber() > 0) {
    gm.insertCoin();
    gm.turnCrank();
}

Go to the full post

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