设计模式【七】建造者模式

建造者模式:将构建一个复杂的对象与它的表示分离,使得同样的构建构建过程可以有不同的表示。

1、类图

2、实现

public abstract class AbstractExport {

    protected String type;

    protected String name;

    public abstract void buildType();

    public abstract void buildName();

    public final void build() {

        buildType();

        buildName();

        System.out.println("type:" + this.type);
        System.out.println("name:" + this.name);

    }

}


public class AsyncExport extends AbstractExport {


    @Override
    public void buildType() {
        super.type = "async type";
    }

    @Override
    public void buildName() {
        super.name = "async name";
    }
}

public class SyncExport extends AbstractExport {


    @Override
    public void buildType() {
        super.type = "sync type";
    }

    @Override
    public void buildName() {
        super.name = "sync name";
    }
}

public class ExportTest {

    public static void main(String[] args)  {

        AsyncExport asyncExport = new AsyncExport();
        asyncExport.buildName();
        asyncExport.buildType();
        asyncExport.build();

    }

}

3、实际使用

public class BaseCode {
    private static final long serialVersionUID = 1L;
    private String code;
    private Long type;

    public static BaseCode.BaseCodeBuilder builder() {
        return new BaseCode.BaseCodeBuilder();
    }

    public BaseCode(String code, Long type) {
        this.code = code;
        this.type = type;
    }

    public BaseCode() {
    }

    public String getCode() {
        return this.code;
    }

    public Long getType() {
        return this.type;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setType(Long type) {
        this.type = type;
    }

    public static class BaseCodeBuilder {
        private String code;
        private Long type;

        BaseCodeBuilder() {
        }

        public BaseCode.BaseCodeBuilder code(String code) {
            this.code = code;
            return this;
        }

        public BaseCode.BaseCodeBuilder type(Long type) {
            this.type = type;
            return this;
        }

        public BaseCode build() {
            return new BaseCode(this.code, this.type);
        }

        public String toString() {
            return "BaseCode.BaseCodeBuilder(code=" + this.code + ", type=" + this.type + ")";
        }
    }
}

4、lombok中的建造者模式

使用:@Builder
@Builder
public class BaseCode {
private static final long serialVersionUID = 1L;

    /**
     * <pre>
     * 编码
     * </pre>
     * 
     */
    private String code;

    /**
     * <pre>
     * 编码类型:1:BOSS;2:VIP
     * </pre>
     * 
     */
    private Long type;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值