Teaser Image

qnoid

Markos Charatzas - Edinburgh, UK




/**
     * Use it to create survival kits!
     * 
     * Don't be afraid to use the {@link SurvivalKitBuilder} to create your own
     * custom configuration of a kit! 
     */
    public class SurvivalKitFactory
    {
        /**
         * By default a survival kit contains a t-shirt of your specified size, 
         * a mug, a wristband and 2 stickers. Hubba, hubba!
         * 
         * @param size the size of your kit
         * @return a freshly made survival kit just for you
         */
        public SurvivalKit newSurvivalKit(Size size) 
        {
        return new SurvivalKitBuilder()
                .add(
                    new TShirt(size, Material.COTTON), 
                    new Mug(), 
                    new Wristband())
                .add( Collections.nCopies(2, new Sticker(Material.VINYL)) )
                .build();
        }
        
        /**
         * @return a SurvivalKit without the TShirt
         */
        public SurvivalKit newValueSurvivalKit() 
        {
        return new SurvivalKitBuilder()
            .add(
                new Mug(), 
                new Wristband())
            .add( Collections.nCopies(2, new Sticker(Material.VINYL)) )
            .build();
        }
    }

The builder for the SurvivalKit came handy for as long as we had only a single configuration to create.

However, defining the SurvivalKitItem now allows us to have kits with varying items. Thus different configurations.

So how can our builder accomodate for that change? Let's find out.

You could put in a flag along with a switch statement which produces a different kit every time but that would mean that you are abusing the if. Could you use the Strategy pattern then in the same manner? You could, but there is a much more elegant way to go about it, that is use a factory.

You might think that the factory makes the builder obsolete. Far from it. It's actually complementary by using the builder to create different configurations for the kit.

Notice how the builder provides the methods to customize the kit in addition to reasonable constants and defaults. The factory on the other hand holds all the new operators that make up a kit each time.

Not only you have encapsulated construction of the SurvivalKit that way but also provided custom instances.

Be careful not to abuse it by providing every possible custom configuration for the kit. Your client code should still be able to use the builder as intended.