设计模式笔记_创建型_建造者模式

1. 建造者模式介绍

建造者模式是一种创建型设计模式,旨在通过将复杂对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。它通常用于构造步骤固定但具体实现可能变化的对象。

1.1 功能:

  1. 封装复杂对象的创建过程 :适用于需要多个步骤来创建一个复杂对象的情况。
    • 一个类中有些属性属于必填的,这些必填信息需在创建对象时做校验;
    • 有些属性之间有依赖关系或约束条件,在创建对象时需对多个属性做联合约束校验
  2. 提高代码可读性和可维护性 :通过分离构建逻辑和表示逻辑,代码更加清晰。
    • 一个类中有很多属性,使用构造函数,会导致参数列表过长,影响代码的可读性和易用性
  3. 支持不可变对象的创建 :可以在对象构建完成后一次性设置所有属性,避免部分初始化的状态。
    • 希望创建不可变对象,在对象在创建好之后,就不能再修改内部的属性值

1.2 用法:

step1. 目标类提供一个私有构造函数,只能通过 Builder 来实例化。

step2. 定义一个 Builder 类负责构建目标对象,属性与目标类一致,逐步设置各个参数。

2. 代码演示

场景说明:新建一个 Computer对象,要求:

  1. 其 cpu、ram、storage属性是必有的
  2. storage值不能小于0,默认值为1024;
  3. name和code属性可空,但不能同时为空。

Computer比较符合建造者模式使用条件,对应代码如下:

java 复制代码
public class Computer {
    private String cpu;
    private String ram;
    private Long storage;
    private String name;
    private String code;

    //目标类私有构造函数,必须使用Builder来创建目标类对象
    private Computer(Builder builder) {
        this.cpu = builder.cpu;
        this.ram = builder.ram;
        this.storage = builder.storage;
        this.name = builder.name;
        this.code = builder.code;
    }

    public static class Builder {
    	//Builder属性与目标类Computer属性一致
        private String cpu;
        private String ram;
        private Long storage = 1024L; // 默认值
        private String name;
        private String code;

		//设置属性时,做相关校验
        public Builder setCpu(String cpu) {
            if (cpu == null || cpu.isEmpty()) {
                throw new IllegalArgumentException("CPU cannot be null or empty");
            }
            this.cpu = cpu;
            return this;
        }

        public Builder setRam(String ram) {
            if (ram == null || ram.isEmpty()) {
                throw new IllegalArgumentException("RAM cannot be null or empty");
            }
            this.ram = ram;
            return this;
        }

        public Builder setStorage(Long storage) {
            if (storage == null || storage <= 0) {
                throw new IllegalArgumentException("Storage must be greater than 0");
            }
            this.storage = storage;
            return this;
        }

        public Builder setName(String name) {
            this.name = name;
            return this;
        }
        
        public Builder setCode(String code) {
            this.code = code;
            return this;
        }

        public Computer build() {
            // 创建Computer对象前,做相关校验
            if (this.cpu == null || this.cpu.isEmpty()) {
                throw new IllegalStateException("CPU is not set");
            }
            if (this.ram == null || this.ram.isEmpty()) {
                throw new IllegalStateException("RAM is not set");
            }
            if (this.storage == null || this.storage <= 0) {
                throw new IllegalStateException("Storage is not valid");
            }
            if ((this.name == null || this.name.isEmpty()) && (this.code == null || this.code.isEmpty())) {
                throw new IllegalStateException("Both name and code cannot be empty");
            }
            return new Computer(this);
        }
    }

    @Override
    public String toString() {
        return "Computer{" +
		        "code='" + code + '\'' +
                ", name='" + name + '\'' +
                ", cpu='" + cpu + '\'' +
                ", ram='" + ram + '\'' +
                ", storage=" + storage +
                '}';
    }
}

使用Demo如下:

java 复制代码
public class BuilderDemo {
    public static void main(String[] args) {
        // 使用 Builder 构建一个 Computer 对象
        Computer computer = new Computer.Builder()
                .setCpu("Intel i9")
                .setRam("32GB")
                .setStorage("1024L")
                .setName("MacBook Pro")
                .setCode("123456")
                .build();

        // 打印结果
        System.out.println(computer);
    }
}
相关推荐
Engineer邓祥浩19 分钟前
JVM学习笔记(5) 第二部分 自动内存管理 第4章 虚拟机性能监控、故障处理工具
jvm·笔记·学习
智者知已应修善业37 分钟前
【51单片机4个IO实现16按键可扩展独立按键64矩阵驱动显示矩阵原值】2023-5-8
c++·经验分享·笔记·算法·51单片机
深蓝海拓39 分钟前
S7-1500学习笔记:Array数据类型
笔记·学习·plc
无籽西瓜a41 分钟前
【西瓜带你学设计模式 | 第十二期 - 装饰器模式】装饰器模式 —— 动态叠加功能实现、优缺点与适用场景
java·后端·设计模式·软件工程·装饰器模式
无籽西瓜a1 小时前
【西瓜带你学设计模式 | 第十三期 - 组合模式】组合模式 —— 树形结构统一处理实现、优缺点与适用场景
java·后端·设计模式·组合模式·软件工程
Xudde.9 小时前
班级作业笔记报告0x04
笔记·学习·安全·web安全·php
zzh08111 小时前
MySQL高可用集群笔记
数据库·笔记·mysql
绛橘色的日落(。・∀・)ノ12 小时前
Matplotlib实践学习笔记
笔记·学习
chase。12 小时前
【学习笔记】AGILE:把人形机器人强化学习从“玄学”变成“工程学”
笔记·学习·敏捷流程
Rsun0455112 小时前
设计模式应该怎么学
java·开发语言·设计模式