设计模式笔记——建造者模式

设计模式笔记——建造者模式

设计模式(创建型)—— 建造者模式

这是一个学生类,它有四个属性,通过构造方法创建它的对象,我们需要填入四个参数,这就导致创建对象的代码有点长(如果他有更多属性时,那会更加恐怖),这看起来不太优雅

public class Student {
    public int id;
    public int age;
    public int grade;
    public String name;

    public Student(int id, int age, int grade, String name) {
        this.id = id;
        this.age = age;
        this.grade = grade;
        this.name = name;
    }
}

在之前,我们学习过通过StringBuilder来创建一个字符串,它就像一个建造者,可以这个字符串对象中不断添加、删除、修改,最终得到一个字符串对象,参考这种方法,我们是不是也可以设计一个创建学生对象的建造者(学生类的内部类)

public static class StudentBuilder {
        int id;
        int age;
        int grade;
        String name;

        public StudentBuilder id(int id) {
            this.id = id;
            return this;
        }

        public StudentBuilder age(int age) {
            this.age = age;
            return this;
        }

        public StudentBuilder grade(int grade) {
            this.grade = grade;
            return this;
        }

        public StudentBuilder name(String name) {
            this.name = name;
            return this;
        }

        public Student build() {
            return new Student(id, age, grade, name);
        }
 }

通过一个静态方法,来获取建造者对象

 //获取建造者
public static StudentBuilder builder() {
     return new StudentBuilder();
}

这样一来,我们就可以通过这样一种方式得到一个对象

Student student = Student.builder()
                .id(1)
                .age(16)
                .grade(9)
                .name("张三")
                .build();
System.out.println(student);

这看起来优雅多了,当然如果这个类只有两三个简单的属性,我们依然可以采用最原始的构造方法来创建,建造者模式的优雅在属性特别多时才能很好的体现

转载请说明出处内容投诉
AJ教程_站长资源网 » 设计模式笔记——建造者模式

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买