Is this a good candidate for the factory pattern?

Discussion in 'Mac Programming' started by MorphingDragon, Mar 28, 2014.

  1. MorphingDragon macrumors 603


    Mar 27, 2009
    The World Inbetween
    I'm creating a typesafe front end for a web API and I'm a little stuck at the architecture.

    Basically the API works by having commands. Within the possible commands there are groups eg: Overlay or Scene. Each group has a set of associated actions and *possible* required query data with that action.

    My first thought was to have something like the decorator pattern:
    new Command(new Overlay(new GetMetadata....));

    The main problem is that this is very verbose and also oddly rather weak as an architecture. Not every group action needs a plethora of information. If the API changes it seems like this design would be very klunky to update as well.

    I was thinking that this might be better as a factory pattern, a factory for each group. Although there would need to be a method for every possible action, if changes happened in the API the user wouldn't have to care about it. the implementation could also share code between the factories, maybe even just reusing the possible decorator approach I aimed at above.

    var command = SceneCommandFactory.CreateListByOwner(query, data, here);
    i_CloudAPI.SendCommand(sessionInfo, command, mycallback...);

    Would the factory pattern work here? Or should I look elsewhere.
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Might be better with a builder pattern. The required parameters are passed to the builder's constructor to ensure these are present at compile time. From there you can call chained setters on the builder. Once you call build you'll get back your immutable object that's properly configured.

    final SendCommand myCommand = SendCommand.builder(reqArg1, reqArg2).setOptional1(opt1).setOptional2(opt2).build();
    It's a decent amount of code underneath, but it's easy to use elsewhere. For the above you'd need an inner class Builder, then a factory called builder on the containing class. You'd make SendCommand's constructor private for use by Builder's build method only, then setup a private constructor on Builder that only builder uses. Each set* on the Builder returns this so you can chain.


Share This Page