Should I use the template method or the command pattern to create a hook ?

Sometimes you need to have a hook in your code. This hook allows other developers to make some of their code be executed within yours.

void m() {
    System.out.println("my code");
    // hook
    System.out.println("my code");
}

You have two ways to do that. The first way is the template method pattern and the second is the command pattern.
The template method uses inheritance while the command pattern use composition.

If you use the template method your code will be as follows :

abstract class A {
    void m() {
        System.out.println("my code");
        hook();
        System.out.println("my code");
    }
    void abstract hook();
}

class B extends A {
    void hook() {
        System.out.println("hook code");
    }
}

You can also write a stub implementation :

class A {
    void m() {
        System.out.println("my code");
        hook();
        System.out.println("my code");
    }
    void hook() {}
}

class B extends A {
    void hook() {
        System.out.println("hook code");
    }
}

But Inheritance is static, thus solved at compile-time. If you want a dynamically (run-time) modifiable hook, you have to use composition. You can do that thanks to the Command pattern.

class A {
    private Command command;
    public A(Command command) {this.command = command}
    void m() {
        System.out.println("my code");
        if (command != null) command.hook();
        System.out.println("my code");
    }
}

interface Command { void hook(); }
class StubCommand implements Command { public void hook() {} } // Empty hook
class CommandImpl implements Command {
    public void hook() { System.out.println("hook code"); }
}

There is no particular solution but generally the most reusable solution uses composition.

Advertisements

2 thoughts on “Should I use the template method or the command pattern to create a hook ?

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