buider设计模式

作者 chauncy 日期 2016-12-09
buider设计模式

如果类的构造器或者静态工厂中具有多个参数,设计这种类时,builder模式就一种不错的选择,特别是当大多数参数都是可选的时候,与使用传统的重叠构造器模式相比,用builder模式的代码更好读和可控。 总结一句话,就是在够着一个对象的时候,需要传入一些参赛,但是有些参数是可以传入的,有些又是可以不用传入的,此时用buide模式就OK了
情景: 现在服务端需要推送一条消息给app端,除了推送的标题,内容不一样以外其余的像什么声音啊,图标啊都一样的,所以在构造的推送内容
的时候就运用buider模式了

public class PushContext {

    private String title;
    private String body;
    private Integer badge;
    private String sound;
    private String type;
    private String action;
    private String image;

public static class Builder {
    private String title = "title ";
    private String body = "body ";
    private Integer badge = 1;
    private String sound = "default";
    private String type = AppProtocolEnum.module.name();
    private String action = AppProtocolEnum.module.name();
    private String image = "image";

    public Builder(String type, Integer bizId) {
        this.action = AppProtocolEnum.module.name() + type + "?id=" + bizId;
    }

    public Builder builderTitle(String title) {
        this.title = title;
        return this;
    }

    public Builder builderBody(String body) {
        this.body = body;
        return this;
    }


    public Builder builderSound(String sound) {
        this.sound = sound;
        return this;
    }

    public Builder builderType(String type) {
        this.type = type;
        return this;
    }

    public Builder builderBadge(Integer badge) {
        this.badge = badge;
        return this;
    }


    public Builder builderImage(String image){
        this.image = image;
        return this;
    }

    public Builder builderAction(String action){
        this.action =action;
        return this;
    }

    public PushContext build(){
        return new PushContext(this);
    }


}

private PushContext(Builder builder) {
    this.title = builder.title;
    this.body = builder.body;
    this.badge = builder.badge;
    this.sound = builder.sound;
    this.type = builder.type;
    this.action = builder.action;
    this.image = builder.image;
}

... class  buider的 get set 方法...

}

如下运用:
PushContext pushContext = new PushContext.Builder(AppProtocolModuleEnum.bonus.name(),bonusDO.getId()).build();
messagePush.pushMessageToMember(memberId,pushContext);