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

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

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

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);

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

相关推荐
阿星AI工作室1 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦21 小时前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
西岸行者4 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky4 天前
Django入门笔记
笔记·django
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意4 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
qianshanxue114 天前
计算机操作的一些笔记标题
笔记
土拨鼠烧电路4 天前
笔记11:数据中台:不是数据仓库,是业务能力复用的引擎
数据仓库·笔记
土拨鼠烧电路4 天前
笔记14:集成与架构:连接孤岛,构建敏捷响应能力
笔记·架构