Setters AND ( not OR or VS ) builder patterns

后端 未结 6 1057
一整个雨季
一整个雨季 2021-02-05 23:07

I have a situation where I use a builder pattern for constructing an object. Best example to give is the pizza code

public class Pizza {
  private int size;
  pr         


        
6条回答
  •  孤独总比滥情好
    2021-02-05 23:45

    Let me suggest another couple of options, going further in the direction of the first answers. As has been mentioned, the virtues of the builder pattern include the ability to accumulate knowledge over multiple steps, support for immutable instances, and to ensure that a "fresh" object is created in a coherent state. I'll stay within the concepts of your question's design.

    1. You could extend the Pizza class by an instance method (e.g. withCheese(boolean value) that returns a new Pizza instance whose other attributes match those of the receiving instance but with the specified cheese attribute value. This preserves immutability of the original, but gives you a new instance with the intended difference.

    2. You could extend the Pizza class by an instance method (e.g. builder() that returns a Pizza.Builder initialized with the attributes of the receiving instance. Then all the methods already on Pizza.Builder are available, without needing to add instance methods per option 1. The cost of that benefit is the need to make a final build() call on the Pizza.Builder.

    So after executing

    Pizza pizza0 = new Pizza.Builder(10)
        .cheese(true)
        .build();
    

    to get a ten-inch cheese pizza, you could execute

    // option 1
    Pizza pizza1 = pizza0.withPepperoni(true);
    

    to get a ten-inch cheese-and-pepperoni pizza via option 1, or

    // option 2
    Pizza pizza2 = pizza0.builder().pepperoni(true).build();
    

    to get the same thing via option 2.

    Option 1 is shorter to get a new pizza with a single difference, but takes more effort to implement all the needed instance methods and builds more intermediate pizzas to make multiple differences.

    Option 2 always gets a Pizza.Builder but then reuses all of its capabilities to get a single resulting pizza in the desired configuration. This option also allows more pizza attributes to be added more easily (by adding the instance attribute to Pizza and the single corresponding method to Pizza.Builder.

提交回复
热议问题