Builder design pattern: Why do we need a Director?

后端 未结 7 1968
梦如初夏
梦如初夏 2020-12-13 18:10

Recently I\'ve come across the Builder design pattern. It seems that different authors use \"Builder pattern\" to refer to different flavours, so let me describe the pattern

7条回答
  •  隐瞒了意图╮
    2020-12-13 18:32

    If you separate into Director and Builder you have documented the different responsibility of assembling a product from a set of parts (director) and the responsibility of creating the part (builder).

    • In the builder you can change how a part is build. In your case whether a AddLiquid() should add cream or milk.
    • In the director you can change how to assemble the parts. In your case a by using AddChocolate() instead of AddFruits() you get a different cake.

    If you want this extra flexibility, I would rename to (since using baker in the builder suggests, it was the builders job of assembling the parts)

    class LightBakingSteps : public BakingSteps {
    public:
        virtual void AddLiquids()
        {
            // Add milk instead of cream
        }
    
        virtual void AddDryIngredients()
        {
            // Add light sugar
        }
    
        ...
    };
    
    class ChoclateCakeBaker : public CakeBaker {
    public:
         Cake Bake(BakingSteps& steps)
         {
             steps.AddLiquieds();
             steps.AddChocolate();      // chocolate instead of fruits
             return builder.getCake();
         }
    }
    

提交回复
热议问题