Setters AND ( not OR or VS ) builder patterns

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

    You've never seen that used because most of the time, the builder pattern is used to build an immutable object.

    But I don't see why they couldn't coexist. The builder builds an object, and you want the built object to be mutable, then it can have setters. But then, if it is mutable and has setters, why not build the object using a simple constructor, and call setters to change the state? The builder isn't really useful anymore, unless only one or two fields among many are mutable.

提交回复
热议问题