简体   繁体   中英

Effective Java. Serializable Builder pattern (how to add public no-arg constructor?)

I want to create a class in Joshua Bloch's style using Builder pattern. But I want to use this class as DTO object and transfer it from EJB. So it need to have public no-arg constructor. How I can achieve this java-bean style in builder pattern? In Effective Java object have only one constructor which accepts Builder object as argument. If I add there public no-arg constructor, then I lost advantage of builder over Java-bean pattern.

Not sure what is making you to use builder pattern here but here is what my experience says to your issue.

  1. You are using EJBs. So, i assume that you are in distributed application mode.
  2. Your DTO will be used for carrying data to and from EJB. So, you should consider making your this DTO serializable (Now, having a no argument constructor makes sense).

According to me, all you need is some kind of transformer which accepts obj1 from some layer for processing and then return it.

I would recommend builder to be used only in case where your object construction is a multi-step process (for example, user registration).

If you use Lombok to create @Builder implementation. You can use @Jacksonized annotation for serialization and deserialization. read more in the official docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM