Home

Code using proper behaviour patterns use interfaces to their best advantage. Classes are not burdened with the specifics of setting up external objects, they are free to focus on their own concerns. This high cohesion leads to great readability and flexibility.

Strategy

If I give you a pack of cards to shuffle, my only requirement is that the cards are reordered randomly. There are many ways to achieve this objective and I leave this choice up to you. In the Strategy Pattern a class delegates certain methods to another specialised class, which can also then be swapped at run-time.

interface Shuffler {
    void Shuffle(Pack);
}

class Reader implements Shuffler {
    void Shuffle(Pack) {
        // (Some kind of groovy shuffle)
    }
}

cards3

Observer

An Observer object registers with a Subject object. The Subject object then adds the Observer to a list. The next time a certain event happens to the Subject, the Subject calls a method on the Observer with some information. This is a brilliant way of reducing the coupling between a Subject and an Observer and allowing Observers to be added and removed at will.

interface Observable {
    void notify(String s);
}

class Observer implements Observable {
    Observer(Subject subject) {
        subject.register(this);
    }

    @Override
    void notify(String s) {
        System.out.println(s);
    }
}

class Subject {
    List<Observable> observers = new ArrayList<Observable>();

    void register(Observable observer) {
        observers.add(observer);
    }

    void interrupt() {
        for (Observable o : observers) {
            o.notify("I've been notified of an interruption");
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s