Builder pattern vs. config object

后端 未结 9 424
执笔经年
执笔经年 2021-01-31 08:40

The builder pattern is popular to create immutable objects, but there is some programming overhead to create a builder. So I wonder why not simply using a config object.

9条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 09:36

    The configuration pattern and the builder pattern are functionally equivalent. They both solve the same problems -

    • Eliminate the need for multiple constructor signatures

    • Allow fields to only be set during construction

    • Allow consumers to only set values they care about and have logical defaults for the other values

    Anything you want to do in one of these patterns you can do in the other, such as only allowing state to be set with methods that do validation and setting state with encapsulated logic. The only real difference is if you like creating objects with the new key term or if you like calling a .build() method.

提交回复
热议问题