Builder模式是一种一步一步创建一个复杂对象的设计模式,这种设计模式的精髓就主要有两点:其一,用户使用简单,并且可以在不需要知道内部构建细节的情况下,就可以构建出复杂的对象模型;其二,对于设计者来说,这是一个解耦的过程,这种设计模式可以将构建的过程和具体的表示分离开来。
builder模式的最终目的为创建对象。
相同的方法,不同的执行顺序,产生不同的时间结果
多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不同时
产品类非常复杂,或者产品类中的调用顺序不同产生了不同的作用,这个时候用建造者模式非常适合
当初始化一个对象特别复杂,如参数多,且很多参数都具有默认值
例子:
public class Aliyun {
private String appKey;
private String appSecret;
private String bucket;
private String endPoint;
private final String description = "阿里云-OSS";
public static class Builder{
private String appKey;
private String appSecret;
private String bucket;
private String endPoint;
public Builder appKey(String appKey){
this.appKey = appKey;
return this;
}
public Builder appSecret(String appSecret){
this.appSecret = appSecret;
return this;
}
public Builder bucket(String bucket){
this.bucket = bucket;
return this;
}
public Builder endPoint(String endPoint){
this.endPoint = endPoint;
return this;
}
public Aliyun build(){
return new Aliyun(this);
}
}
public static Builder builder(){
return new Aliyun.Builder();
}
private Aliyun(Builder builder){
this.appKey = builder.appKey;
this.appSecret = builder.appSecret;
this.bucket = builder.bucket;
this.endPoint = builder.endPoint;
}
public String getAppKey() {
return appKey;
}
public String getAppSecret() {
return appSecret;
}
public String getBucket() {
return bucket;
}
public String getEndPoint() {
return endPoint;
}
public String getDescription() {
return description;
}
}
例子:
@Builder
@ToString
public class User {
private String name;
private String phone;
private final String country = "中华人民共和国";
}
@Bean
public Aliyun aliyun(){
return Aliyun.builder()
.appKey(appKey)
.appSecret(appSecret)
.bucket(bucket)
.endPoint(endPoint)
.build();
}
原文:https://www.cnblogs.com/speily/p/10937023.html