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

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

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

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 小时前
随笔|走!跳楼去!
笔记
就叫飞六吧1 小时前
国产数据库gbase8s安装-网盘
笔记
敲代码的约德尔人1 小时前
JavaScript 设计模式完全指南
javascript·设计模式
网络工程小王2 小时前
【大数据技术详解】——Kibana(学习笔记)
大数据·笔记·学习
努力的lpp2 小时前
2024小迪安全课程第四节复习笔记
笔记·安全
雷工笔记4 小时前
AI使用|通过AI学习物料分类编码表
笔记·学习
Shea的笔记本4 小时前
MindSpore实战笔记:WaveNet音乐生成复现全记录
笔记
koo3644 小时前
pytorch深度学习笔记23
pytorch·笔记·深度学习
FakeOccupational5 小时前
【电路笔记 STM32】Cortex-M7 内核上的数据缓存结构图 + MPU内存保护单元 + Cache基本操作 + Cache&DMA 时序图
笔记·stm32·缓存