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

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

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

java 复制代码
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来创建一个字符串,它就像一个建造者,可以这个字符串对象中不断添加、删除、修改,最终得到一个字符串对象,参考这种方法,我们是不是也可以设计一个创建学生对象的建造者(学生类的内部类)

java 复制代码
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);
        }
 }

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

java 复制代码
 //获取建造者
public static StudentBuilder builder() {
     return new StudentBuilder();
}

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

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

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

相关推荐
強云1 小时前
23种设计模式 - 模板方法
设计模式·模板方法
东方芷兰2 小时前
伯克利 CS61A 课堂笔记 11 —— Mutability
笔记·python
快下雨了L7 小时前
C++面试笔记(持续更新...)
笔记
workflower7 小时前
Prompt Engineering的重要性
大数据·人工智能·设计模式·prompt·软件工程·需求分析·ai编程
柃歌8 小时前
【UCB CS 61B SP24】Lecture 7 - Lists 4: Arrays and Lists学习笔记
java·数据结构·笔记·学习·算法
JANGHIGH8 小时前
c++ std::list使用笔记
c++·笔记·list
柃歌8 小时前
【UCB CS 61B SP24】Lecture 4 - Lists 2: SLLists学习笔记
java·数据结构·笔记·学习·算法
大溪地C8 小时前
Git 合并冲突解决与状态分析笔记
笔记·git
BUG 劝退师9 小时前
C语言预处理学习笔记
c语言·笔记·学习
ox008011 小时前
C++ 设计模式-中介者模式
c++·设计模式·中介者模式