程序员经常会遇到灵魂拷问:你有对象吗?没有,但我可以 new 一个!
1 | public class GirlFriend { |
没问题,老铁!但如果对象的属性太多,咋办?
1 | public class GirlFriend { |
1 | GirlFriend{name='小美' |
GirlFriend 是很美,但写起来也太麻烦了吧。说说缺点:实例化和设置属性分开,不好维护,变量名重复写。这里不再介绍其他 Builder 实现方式,直接祭出最实用的通用 Builder。适用于所有类,不需要改造原来类,不需要 lombok 插件支持。先看看使用姿势:
1 | public class GirlFriend { |
看到了吗!实例化和属性设置在同一条语句执行,链式操作,一路点点点,清爽!
Builder<T>
Talk is cheap, show me the code:
1 | /** |
这个示例最多支持三个参数的设置属性方法,也完全够用了。如果要扩展也很容易,依葫芦画瓢,添加多个参数的 Consumer。
参考:https://mp.weixin.qq.com/s/OzLqq5M2iC3mO6HZqLsz0A
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !