抽离复杂对象的构造函数,让我们可以通过多种方法的排列组合构建复杂的对象。如果构造器参数过多,可以考虑 builder 模式
这样说也有点抽象,举个例子吧。
比如 非常热门的消息队列rabbitmq 的 amqp.basicproperties
因为它的属性比较多,所以构造函数也是挺吓人的。
我看到也不太想调用。
如果现在要构造一条消息
在没有 builder 模式之前,是这样构造的
new amqp.basicproperties("text/plain",null,null,2,1,null,null,null,null,null,null,null,null,null);
痛苦啊!!!不信,你自己也可以尝试构造一下。
而用了 builder 模式后。
new amqp.basicproperties.builder() .contenttype("text/plain") .deliverymode(2) .priority(1) .build();
舒畅!!!
很简单。
basicproperties
中添加一个叫builder
的内部类basicproperties
类是完全一致的builder
实例在调用build
函数的时候,再调用basicproperties
的构造函数构造对象。代码如下
public static class basicproperties{ private string contenttype; private string contentencoding; private map<string,object> headers; private integer deliverymode; private integer priority; //... 还有很多属性 public basicproperties( string contenttype, string contentencoding, map<string,object> headers, integer deliverymode, //... string clusterid){ this.contenttype = contenttypel; this.contentencoding = contentencoding; //... } public static final class builder { private string contentencoding; private map<string,object> headers; private integer deliverymode; private integer priority; //.. 和basicproperties的字段一致的。 public builder contenttype(string contenttype){ this.contenttype = contenttype; return this; } public builder contentencoding(string contentencoding){ this.contentencoding = contentencoding; return this; } public basicproperties build() { return new basicproperties ( contenttype contentencoding, //还有很多属性 ); } } }
builder 模式的好处
坏处
如果不用 builder 模式,有其他的做法吗?
比如,上面的例子,我构造的消息只需 投递模式(delivery mode)、优先级(priority)、 content-type ,专门为这几个参数弄个专门的构造函数,可以吗?
调用就变成这样了。
new amqp.basicproperties("text/plain",2,1)
可以,
basicproperties p = new amqp.basicproperties(); p.setcontenttype("text/plain"); p.setdeliverymode(2); p.setpriority(1);
在《effective java》中就探讨过这个可能,书中是这样说的
因为构造过程被分到几个调用中,在构造过程中 javabean 可能处于不一致的状态。类无法仅仅通过检验构造器参数的有效性来保证一致性。试图使用处于不一致状态的对象,将导致失败,这种失败与包含错误的代码大相径庭,因此它调试起来十分困难。与此相关的另一点不足在于,javabeans 模式阻止了把类做成不可变的可能,这需要程序员付出格外的努力来确保它的线程安全。
这话就有点摸不着头脑,什么意思。读了几次也有点懵。
其实意思是大概的,
以上
如对本文有疑问, 点击进行留言回复!!
软件设计模式六大原则-接口隔离原则 Interface Segregation Principle
设计模式之解释器模式(附:SpelExpressionParser中解释器模式应用分析)
网友评论