Design Pattern: Builder

前端 未结 4 2024
粉色の甜心
粉色の甜心 2020-12-14 07:43

I have looked for a good example of a Builder pattern (in C#), but cannot find one either because I don\'t understand the Builder pattern o

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 08:39

    I am going refer to the C# example in the Wikipedia Article here.

    First problem is most examples hard code property values in to the concrete parts, which I really think should come from a database. I thought the idea was to send my choices to the Director (from a data source) and have the builder create a customized product based on my data.

    In this case you would have class implementing PizzaBuilder that knows how to retrieve data from a database. You can do it several ways.

    One would be make a HawaiianPizzaBuilder. When the class initializes it queries the database for a Hawaiian Pizza and retrieves the row. Then when the various Build(x) methods are called it would set the properties to the corresponding field of the retrieved database row.

    Another would be just makes a PizzaDatabaseBuilder and make sure that when you initialize the class you pass it the ID of the row you need for that type of pizza. For example instead of

    waiter.PizzaBuilder = new HawaiianPizzaBuilder();
    

    You use

    waiter.PizzaBuilder = new PizzaDatabaseBuilder("Hawaiian");
    

    Second problem is I want the builder methods to actually create the parts then assign them to the product, not pass strings but real strongly typed product parts.

    Should not be an issue. What you need is an other Factory/Builder type pattern to initialize the fields of the Pizza. For example

    instead of

     public override void BuildDough()   { pizza.Dough   = "pan baked"; }
    

    you would do something like

     public override void BuildDough()   { pizza.Dough   = new DoughBuilder("pan baked"); }
    

    or

     public override void BuildDough()   { pizza.Dough   = new PanBakedDoughBuilder(); }
    

    DoughBuilder can go to another table in your database to properly fill out a PizzaDough Class.

提交回复
热议问题