

设计模式—建造者模式(Builder)
source link: http://www.cnblogs.com/muggle0/p/12585896.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

title: 设计模式—建造者模式
建造者模式(Builder)是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。建造者模式属于对象创建型模式。我们获得一个对象的时候不是直接new这个对象出来,而是对其建造者进行属性设置,然后建造者在根据设置建造出各个对象出来。建造者模式又可以称为生成器模式。
模式结构
一个标准的建造者模式包含如下角色:
- Builder:抽象建造者
- ConcreteBuilder:具体建造者
- Director:指挥者
- Product:产品角色
源码导读
建造者模式使用比较简单,场景也比较清晰。protobuf中protobuf对应的java类就是使用建造者模式来创建对象的。
public static PersonEntity.Person create() { PersonEntity.Person person = PersonEntity.Person.newBuilder() .setId(1) .setName("Pushy") .setEmail("[email protected]") .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那么使用建造者模式就很方便,一个注解搞定。
Recommend
-
45
Builder 建造者模式是5种创建型模式中的一种,重复那句话,既然是创建型模式,他的目的就是用来“构建其它对象“的。但Builder,通常是用于”构建“复杂的对象,并强制一步一步构建的过程,来生成复杂的对象。概念:
-
36
建造者模式(Builder Pattern):将复杂对象的创建和表示分离,使同样的构建过程可以创建不同的表示。 进一步说,建造者隐藏了产品是如何组装的,使建造代码和表示代码分离。建造对象时 构件顺序稳定 的情况下,...
-
27
关于建造者模式,网上已经有很多比较完善的例子,这里为了完善自己对于设计模式的内容,再简单讲解一下吧,方便自己回顾,也为了设计模式专题不遗漏任何一个设计模式 基本介绍 : 建...
-
34
-
29
建造者模式 GitHub代码链接 建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象...
-
18
一 引言 说明:如果想要直接阅读定义等理论内容,可以直接跳转到第二大点 在生活中有很多场景与我们今天要说的 “建...
-
3
-
13
大家好,我是狼王,一个爱打球的程序员 这是设计模式的第四篇,这篇让我们来认识一下 建造者模式 1、概述 建造者模式是一种创建型设计模式, 使你能够分步骤创建复杂对象...
-
7
将一个复杂对象的创建与他的表示分离,使得同样的构建过程可以创建不同的表示1.需要生成的对象具有复杂的内部结构;2.需要生成的对象内部属性本身相互依赖;3.与不可变对象配合使用;1.建造者独立,易扩展;2.便于控制细节...
-
2
Hello,又是拖了几天更,实在是忙的要死,有时候忙累了,真的就是倒头睡的那种,刚好今天闲下来了。今天来更新一篇建造者模式。 其实建造者模式,我们已经在上一节已经有了解过了。只不过是上一节没有提到这样的一个概念。可能大家都觉得抽象工厂模式一般...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK