建造者模式之项目运用

1 问题

建造者模式,我们也许不陌生,因为我们看到很多开源框架或者Android源码里面用到,类似这样的代码结构

A a = new A.builder().method1("111").method2("222").build();

很明显,一般这里的结构有builder()构造函数,还有build()函数,主要用来干嘛呢?还不是为了构建对象,如果需要设置的参数很多的话,一个一个去set很繁琐也不好看,下面有个例子简单粗暴展示。

 
2 测试代码实现

    package com.example.test1;
     
    public class Student {
        private int id;
        private String name;
        private int age;
        private String classNmae;
     
        public Student(Builder builder) {
            this.id = builder.id;
            this.name = builder.name;
            this.age = builder.age;
            this.classNmae = builder.classNmae;
        }
        public int getId() {
            return id;
        }
     
        public String getName() {
            return name;
        }
     
        public int getAge() {
            return age;
        }
     
        public String getClassNmae() {
            return classNmae;
        }
     
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", classNmae='" + classNmae + '\'' +
                    '}';
        }
     
        public static class Builder {
            private int id;
            private String name;
            private int age;
            private String classNmae;
     
            public Builder() {}
            public Builder id(int id) {
                this.id = id;
                return this;
            }
            public Builder name(String name) {
                this.name = name;
                return this;
            }
            public Builder age(int age) {
                this.age = age;
                return this;
            }
            public Builder className(String classNmae) {
                this.classNmae = classNmae;
                return this;
            }
            public Student build() {
                return new Student(this);
            }
        }
    }

                    Student student = new Student.Builder()
                    .name("chenyu")
                    .age(28)
                    .id(1)
                    .className("erzhong")
                    .build();
            Log.i(TAG, "student toString is:" + student.toString());

 
3 运行结果

18376-18376/com.example.test1 I/chenyu: student toString is:Student{id=1, name='chenyu', age=28, classNmae='erzhong'}


4 总结

1)我们需要构建一个对象很多参数的时候用这种方式

2)最关键的是需要构建的对象类里面有个Builder类作为参数传递

        public Student(Builder builder) {
            this.id = builder.id;
            this.name = builder.name;
            this.age = builder.age;
            this.classNmae = builder.classNmae;
        }

3)最后build()函数里面返回的是需要构建的类本身

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


 

 

作者:chen.yu
深信服三年半工作经验,目前就职游戏厂商,希望能和大家交流和学习,
微信公众号:编程入门到秃头 或扫描下面二维码
零基础入门进阶人工智能(链接)