title: 设计模式—建造者模式
建造者模式(builder)是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。建造者模式属于对象创建型模式。我们获得一个对象的时候不是直接new这个对象出来,而是对其建造者进行属性设置,然后建造者在根据设置建造出各个对象出来。建造者模式又可以称为生成器模式。
一个标准的建造者模式包含如下角色:
建造者模式使用比较简单,场景也比较清晰。protobuf中protobuf对应的java类就是使用建造者模式来创建对象的。
public static personentity.person create() { personentity.person person = personentity.person.newbuilder() .setid(1) .setname("pushy") .setemail("1437876073@qq.com") .build(); system.out.println(person); return person;}
一般建造者模式结合链式编程来使用,代码上更加美观。
spring security`中也有使用到建造者模式,其 `authenticationmanagerbuilder`是 `authenticationmanager`的建造者,我们可以通过配置 `authenticationmanagerbuilder`来建造一个 `authenticationmanager public class securityconfig extends websecurityconfigureradapter { @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(userdetailsservice).passwordencoder(passwordencoder); }}
我们来看看 authenticationmanagerbuilder
public class authenticationmanagerbuilder extends abstractconfiguredsecuritybuilder<authenticationmanager, authenticationmanagerbuilder> implements providermanagerbuilder<authenticationmanagerbuilder> { ...... ...... public final authenticationmanager build() throws exception { if (this.building.compareandset(false, true)) { this.object = this.dobuild(); return this.object; } else { throw new alreadybuiltexception("this object has already been built"); } }}
这里抽象建造者是 providermanagerbuilder
,具体建造者是 authenticationmanagerbuilder
,被建造的对象是 authenticationmanager
建造方法是 build()
方法。
一般建造者模式中建造者类命名以 builder
结尾,而建造方法命名为 build()
。
lombok中@builder就是对实体类使用创造者模式,如果你项目中用到了lombok那么使用建造者模式就很方便,一个注解搞定。
如对本文有疑问, 点击进行留言回复!!
unity的错误解决办法:NullReferenceException: Object reference not set to an instance of an object;tiny proje
Hadoop 之 HDFS (HDFS 数据流的 读写 流程)
听说你一读Spring源码就懵逼?我帮你把架子搭好了,你填就行!
首席架构师推荐:金融保险领域数字化转型实践--如何优雅地修改业务中台中分层应用Maven多模块的版本号?(命令导入式)
[JVM学习之路]一、初识JVM,了解其结构、模型及生命周期
网友评论