1

Let's say I have a builder class (which by the way is not techinically a builder, but it's not a factory either) to generate different rules for a game:

public class RuleBuilder {
    private Game game;

    public RuleBuilder(Game g) {
        game = g;
    }

    public Rule scoreRule() {
        return new ScoreRule(game);
    }

    public Rule playerRule() {
        return new PlayerRule(game);
    }

    // etc...
}

The builder returns instances of subclasses of the Rule class.

If we wanted a third party to define their own rules and add them to the game, what should I change in the design to adapt to this new need?

1

What you describe here is a Factory, which simply offloads the responsibility of object creation to another class. What factory to use is static: known at compile time, does not change.

What you need is an Abstract Factory, where the factory is an interface and the implementation of the factory is unknown until run time. This allows third parties to override the creation logic as needed.

The ideal way to set this up is through a framework such as Spring, where a third-party can very easily configure their factory beans. It would look something like this:

<beans>
  <bean name="RuleBuilder" class="com.dabadaba.RuleBuilder "/>
</beans>

Then a third party can override it like this:

<beans>
  <bean name="RuleBuilder" class="com.someoneelse.RuleBuilder "/>
</beans>

The code would look something like this:

public class RuleBuilder {
  public Rule playerRule() {
    return new SomeOtherPlayerRule(game);
  }
}

Note that the beans should have default constructors, but you can wire up the game instance as well through configuration (this is beyond the scope of your question: consult the Spring documentation if you decide to go that route).

In fact with a bit more effort you don't even need the abstract factory, because Spring can create the objects that the factory creates using a maze of XML and annotations. It can be daunting at first, but once you have it set up it is pretty easy to use and extend.

  • I'm sure you can do this without Spring ? I'm not against Spring, but I wouldn't advocate adopting it just for this – Brian Agnew Apr 22 '16 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.