23大设计模式之--建造者模式

Java 建造者模式(Builder Pattern)是一种创建型设计模式,用于构建复杂对象,将对象的构建过程与其表示分离。该模式的主要思想是将一个复杂对象的构建过程分解为多个步骤,然后通过一个构建者类来协调这些步骤。这使得客户端代码可以以清晰、可读的方式构建对象,同时允许对象的不可变性(对象一旦构建完成,其状态就不能再被修改)。

以下是一个简单的示例,展示如何在 Java 中实现建造者模式:

// 创建产品类
class Computer {
    private String cpu;
    private String ram;
    private String storage;
    private String gpu;

    public Computer(String cpu, String ram, String storage, String gpu) {
        this.cpu = cpu;
        this.ram = ram;
        this.storage = storage;
        this.gpu = gpu;
    }

    // Getter 方法用于获取属性值
    // 注意:没有提供 setter 方法,使对象不可变

    @Override
    public String toString() {
        return "Computer [CPU=" + cpu + ", RAM=" + ram + ", Storage=" + storage + ", GPU=" + gpu + "]";
    }
}

// 创建构建者类
class ComputerBuilder {
    private String cpu;
    private String ram;
    private String storage;
    private String gpu;

    public ComputerBuilder withCPU(String cpu) {
        this.cpu = cpu;
        return this;
    }

    public ComputerBuilder withRAM(String ram) {
        this.ram = ram;
        return this;
    }

    public ComputerBuilder withStorage(String storage) {
        this.storage = storage;
        return this;
    }

    public ComputerBuilder withGPU(String gpu) {
        this.gpu = gpu;
        return this;
    }

    public Computer build() {
        return new Computer(cpu, ram, storage, gpu);
    }
}

public class BuilderPatternDemo {
    public static void main(String[] args) {
        Computer computer = new ComputerBuilder()
            .withCPU("Intel i7")
            .withRAM("16GB")
            .withStorage("512GB SSD")
            .withGPU("NVIDIA GeForce RTX 3080")
            .build();

        System.out.println(computer);
    }
}

在上述示例中,我们创建了一个 Computer 类表示计算机对象,它具有不可变性。然后,我们创建了一个 ComputerBuilder 类,该类用于构建 Computer 对象。客户端代码可以通过链式方法调用来设置计算机的属性,最后通过 build 方法来创建不可变的 Computer 对象。

建造者模式使得对象构建过程更加灵活,可以根据需求选择性地设置属性,并且可以轻松地添加新属性或步骤。这提高了代码的可读性,并允许创建复杂对象的过程更加可控。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值