Setters AND ( not OR or VS ) builder patterns

后端 未结 6 1055
一整个雨季
一整个雨季 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:36

    I think it could help someone in the future, but what about Copy constructor thou?

    It will not break a contract of the immutability of an object and you will have an option to get a Pizza with different property values.

    So you can basically use two approaches:

    1. Pizza.Builder(pizza).cheese(cheese).build()
    2. Pizza.from(pizza).cheese(cheese).build() as Akash Srivastava suggested

    Both approaches basically expecting a copy constructor of Pizza or even feeding newly created builder instance from pizza parameter properties.

提交回复
热议问题