设计模式:Builder模式

Builder模式

Builder模式是一种一步一步创建一个复杂对象的设计模式,这种设计模式的精髓就主要有两点:其一,用户使用简单,并且可以在不需要知道内部构建细节的情况下,就可以构建出复杂的对象模型;其二,对于设计者来说,这是一个解耦的过程,这种设计模式可以将构建的过程和具体的表示分离开来。

builder模式的最终目的为创建对象。

Builder模式的使用场景

相同的方法,不同的执行顺序,产生不同的时间结果
多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不同时
产品类非常复杂,或者产品类中的调用顺序不同产生了不同的作用,这个时候用建造者模式非常适合
当初始化一个对象特别复杂,如参数多,且很多参数都具有默认值

Builder模式实现的一般步骤:

1、主类内部定义一个公开的静态内部类,一般使用Builder命名;
2、主类构造方法:传参上面定义的内部静态类对象,属性值传递;
3、静态内部类中提供:内部类定义的属性值即为重写主类属性值,命名一般保持一致,提供setter方法,为实现链式调用,返回其本身;
4、静态内部类: 提供方法用于构造主类的方法, 一般使用build();

例子:

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;
    }

}

  

如果项目中有使用lombok的话,可以直接使用@Builder注解来实现

例子:

@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();
    }

  

posted @ 2019-05-28 14:13  呵呵哒。。。  阅读(287)  评论(0编辑  收藏  举报