Saturday, September 18, 2004

Actor/Director

Fellow ThoughtWorker Andrew McCormick pointed out Actor/Director to me, a good pattern he coined. The simple example he casually posted was turning this:

public class TemplateMethodClass {
    public void doSomething() {
        setup();
        yourstuff();
        finish();
    }

    protected void yourStuff() {
    }
}

Into this:

public class DirectorClass {
    public void doSomething() {
        setup();
        Actor actor = getActorForYourStuff();
        finish();
      }

    protected Actor getActorForYourStuff() {
        // other possibilities
        // return new SingleActor();
        // return new MultipleActor(new SingleActor(), new SingleActor())
        return new NullActor();
    }
}

Seeing this, I immediately cleaned up a long-standing solution to the database connection problem, becoming:

public class ConnectionDirector {
    private final ConnectionProvider provider;
    private final ConnectionActor actor;

    public ConnectionDirector(final ConnectionProvider provider,
            final ConnectionActor actor) {
        this.provider = provider;
        this.actor = actor;
    }

    public void doSomething() {
        final Connection conn = provider.openConnection();
        try {
            actor.doSomething(conn);

        } finally {
            provider.closeConnection(conn);
        }
    }
}

Isn't that tidy? Both the connection provider and the connection actor are passed in. As Andrew noted, Dependency injection is probably the most important obvious-in-hindsight idea that's come along recently. And it fits perfectly into the Actor/Director pattern.

(Note to pattern mavens: does Actor/Director duplicate an existing pattern? I find the name to be very intuitive.)

UPDATE: Andrew later noted: Actor/Director is sort of a twist on Chain of Responsibility...or at least along the same lines. Both have the intent of separating what gets done from how it gets done.

No comments: