disadvantages of builder design pattern [closed]

你。 提交于 2019-12-20 17:41:07

问题


What would be the disadvantages of using the builder design pattern. Are there any??

edit - I want to know whether there is any bad consequence of using builder design pattern? As in the GOF book, they have mentioned the good and bad consequences of design patterns. But they haven't mentioned any bad consequence for builder design pattern.


回答1:


It does create more code (and could introduce more complexity) in the DTO than if you had for example contructor arguments and/or setters/getters.

In my opinion this is not a big deal, in most cases there is not a lot of extra code. The builder pattern will be more than worth it if you have an object that has some mandatory and some optional parameters.




回答2:


A pattern is only disadvantageous when the pattern is been abused/misused. I.e. the pattern didn't solve/suit the actual technical/functional problem at all. You should then to look for another pattern to solve the particular problem.

This doesn't specifically apply to the builder pattern, but to design patterns in general.


Update: if you'd be interested to learn about the various design patters (specifically the ones mentioned in the GoF Design Patterns book) and the real world examples in Java API, then you may find this answer: Examples of GoF Design Patterns in Java's core libraries useful. It contains links to Wikipedia articles explaining the patterns in detail.




回答3:


I second Jarle's post.

Else, when it comes to disadvantages:

  • The builder pattern isn't a good match if you have to map the DTO with for example Hibernate or JAXB.
  • If you for some reasons want a mutable object.
  • For small DTOs with two or three fields, it's just overhead and you should rather use a constructor or two. Unless you know/believe the DTO will contain more fields in the future.



回答4:


Builder pattern, when used with the idea in mind to overcome the lack of optional parameters in Java, you lose the static analysis provided by the compiler (and all the nice refactoring features provided by your IDE). This means that you'll detect that some mandatory parameters are missing only at runtime, instead of having your IDE telling you immediately that something is wrong...




回答5:


comparing to telescope constructors

  • loss of static analysis
  • for missing mandatory parameters an exception needs to be thrown and catched somethere
  • if you use boxed types in builders to represent primitive values which are not set yet, then there is a lot of auto-boxing/unboxing going on - which allows for NullPointerExceptions which are hard to spot. No such problem in telescope constructors - you can just pass primitive values.
  • a lot more code


来源:https://stackoverflow.com/questions/2829106/disadvantages-of-builder-design-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!