Clearing doubts about the builder pattern

后端 未结 8 1137
攒了一身酷
攒了一身酷 2020-12-28 22:57

I am learning about the builder pattern, and so far I understood that, it is a great alternative to the commonly patterns used for initialization:

  • Telescopi

8条回答
  •  旧巷少年郎
    2020-12-28 23:12

    What does using a builder here actually gain you?

    Nothing as far as I can see: you could just create a new Product and use the getters and setters on it directly. If you have a simple POJO then there is absolutely nothing wrong with:

    Product p=new Product();
    p.setColour("Black");
    p.setPrice(11);
    doSomethingWith(p);
    

    Saving a few characters of typing is IMHO not worth introducing a new class / builder abstraction.

    Builders are more useful in situations like the following:

    • You want to create an immutable object (and hence can't use setters)
    • If you have complicated factory logic that cannot easily be expressed with simple getters and setters or that you want to re-use in different ways
    • (Occasionally) when you want to have different parts of the code base configure different aspects of the builder for some reason.

提交回复
热议问题