java建造者模式 (Builder Pattern)示例代码

建造者模式是一种创建型设计模式,它允许我们按照步骤或顺序构建复杂对象。**这种模式特别适用于构建包含许多参数的对象。**建造者模式通过一个建造者对象负责构建目标对象,客户端代码可以根据需要灵活地指定要构建的对象的属性。

产品类

首先,我们定义了产品类 Product,它包含了一些属性:

复制代码
public class Product {
    private String part1;
    private String part2;
    private String part3;

    public void setPart1(String part1) {
        this.part1 = part1;
    }

    public void setPart2(String part2) {
        this.part2 = part2;
    }

    public void setPart3(String part3) {
        this.part3 = part3;
    }

    @Override
    public String toString() {
        return "Product{" +
                "part1='" + part1 + '\'' +
                ", part2='" + part2 + '\'' +
                ", part3='" + part3 + '\'' +
                '}';
    }
}

建造者类

然后,我们定义了建造者类 ProductBuilder,它负责构建 Product 对象:

复制代码
public class ProductBuilder {
    private Product product;

    public ProductBuilder() {
        this.product = new Product();
    }

    public ProductBuilder withPart1(String part1) {
        product.setPart1(part1);
        return this;
    }

    public ProductBuilder withPart2(String part2) {
        product.setPart2(part2);
        return this;
    }

    public ProductBuilder withPart3(String part3) {
        product.setPart3(part3);
        return this;
    }

    public Product build() {
        return product;
    }
}

客户端代码

最后,我们可以在客户端代码中使用建造者模式来构建 Product 对象:

复制代码
public class Client {
    public static void main(String[] args) {
        Product product = new ProductBuilder()
                .withPart1("Part 1")
                .withPart2("Part 2")
                .withPart3("Part 3")
                .build();

        System.out.println(product);
    }
}

示例说明

  • Product 类是要构建的对象,它具有一些属性,例如 part1part2part3
  • ProductBuilder 类负责构建 Product 对象。它提供了一系列的 withXxx() 方法,用于设置 Product 的属性,并且返回 ProductBuilder 实例以支持方法的链式调用。最后,通过 build() 方法返回构建完成的 Product 对象。
  • 使用建造者模式,客户端代码可以根据需要选择设置哪些属性,而不需要关心 Product 对象的构建细节。
相关推荐
ACEEE122212 分钟前
Stanford CS336 | Assignment 2 - FlashAttention-v2 Pytorch & Triotn实现
人工智能·pytorch·python·深度学习·机器学习·nlp·transformer
2501_9262279425 分钟前
UDP网络编程:【Java】无连接通信到Socket实战(二)
java·网络·udp
Sunny_yiyi37 分钟前
Java根据模版导出PDF文件
java·开发语言·pdf
麦兜*39 分钟前
MongoDB 与 GraphQL 结合:现代 API 开发新范式
java·数据库·spring boot·mongodb·spring·maven·graphql
shan&cen42 分钟前
Day02 集合 | 30. 串联所有单词的子串、146. LRU 缓存、811. 子域名访问计数
java·数据结构·算法·缓存
iChochy1 小时前
[开源免费] iGTTS(Gemini TTS) 文本转语音(TTS)的命令行工具。
python·tts·gemini
TwoAI1 小时前
Scikit-learn:从零开始构建你的第一个机器学习模型
python·机器学习·scikit-learn
跟橙姐学代码1 小时前
Python里的“管家婆”:带你玩转os库的所有神操作
前端·python·ipython
倔强青铜三1 小时前
最强Python Web框架到底是谁?
人工智能·python·面试