设计模式-建造者

应用场景:某些类在构建的时候需要传递多个参数,或者含有大量的可选参数时,使用普通的构造器时,如果参数数量过多,那参数传递的顺序和含义记忆起来就会比较麻烦。如果包含着大量的可选参数,那每次构建类时传递这些无实际作用的参数就显得没有意义,这个时候构建器是比较合适的选择。

比如一个消息类Message ,实际构建的时候并不是所有的字段都会用的

public class Message {

    private final String message;
    private final String pic;
    private final String voice;
    private final int voiceLength;
    private final int method;

    public static class Builder {

        private String message = "";
        private String picUrl = "";
        private String voiceUrl = "";
        private int voiceLength = 0;
        private int method = 0;


        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        public Builder setPicUrl(String picUrl) {
            this.picUrl = picUrl;
            return this;
        }

        public Builder setVoiceUrl(String voiceUrl) {
            this.voiceUrl = voiceUrl;
            return this;
        }

        public Builder setVoiceLength(int voiceLength) {
            this.voiceLength = voiceLength;
            return this;
        }

        public Builder setMethod(int method) {
            this.method = method;
            return this;
        }

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

    private Message(Builder builder) {
        this.method = builder.method;
        this.message = builder.message;
        this.pic = builder.picUrl;
        this.voice = builder.voiceUrl;
        this.voiceLength = builder.voiceLength;
    }

}

调用方式

public class MainActivity extends Activity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Message message = new Message.Builder()
                .setMessage("hello world")
                .setMethod(1)
                .build();

        Message message1 = new Message.Builder()
                .setPicUrl("")
                .setMethod(2)
                .build();

        Message message2 = new Message.Builder()
                .setVoiceUrl("")
                .setVoiceLength(0)
                .setMethod(3)
                .build();
    }
}

参数的含义变得更加明确

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yutoudoufu123/article/details/52369480
文章标签: 设计模式 Android
个人分类: Java基础-设计模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭