建造者模式学习笔记

概述

建造者模式是一种创建型设计模式。该模式允许您创建不同类型的对象,同时将对象的构造过程与其表现分离开来。

建造者模式可以帮助您更好地组织代码,因为它将对象创建的代码从主要业务逻辑中分离出来,从而使代码更易于阅读和维护。

实例

在我们的实例中,我们将创建一个“Computer”类,该类表示一台计算机。该计算机具有以下属性:

  • CPU
  • GPU
  • 内存
  • 存储空间
  • 显示器

我们还将创建一个“ComputerBuilder”类,该类用于构建计算机对象。在构建计算机时,我们将使用不同的部件配置来创建不同类型的计算机。

下面是我们的代码实现:

javaCopy Code
public class Computer { private String cpu; private String gpu; private int memory; private int storage; private String monitor; public Computer(String cpu, String gpu, int memory, int storage, String monitor) { this.cpu = cpu; this.gpu = gpu; this.memory = memory; this.storage = storage; this.monitor = monitor; } // getters and setters } public class ComputerBuilder { private String cpu; private String gpu; private int memory; private int storage; private String monitor; public ComputerBuilder withCPU(String cpu) { this.cpu = cpu; return this; } public ComputerBuilder withGPU(String gpu) { this.gpu = gpu; return this; } public ComputerBuilder withMemory(int memory) { this.memory = memory; return this; } public ComputerBuilder withStorage(int storage) { this.storage = storage; return this; } public ComputerBuilder withMonitor(String monitor) { this.monitor = monitor; return this; } public Computer build() { return new Computer(cpu, gpu, memory, storage, monitor); } } public class Main { public static void main(String[] args) { Computer computer = new ComputerBuilder() .withCPU("Intel i7") .withGPU("Nvidia GeForce RTX 3080") .withMemory(16) .withStorage(512) .withMonitor("ASUS ROG Swift PG279QZ") .build(); System.out.println("Computer: " + computer.toString()); } }

在这个实例中,我们使用了建造者模式来构建计算机对象。我们创建了一个“Computer”类和一个“ComputerBuilder”类,其中“ComputerBuilder”类用于构建计算机对象。

在“ComputerBuilder”类中,我们定义了几个方法,以便我们可以设置计算机对象的各个属性。然后,我们通过调用“build()”方法来创建计算机对象。

在我们的示例中,我们使用了不同的部件配置来创建一个名为“computer”的计算机对象。