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 对象的构建细节。
相关推荐
2301_78731243几秒前
MySQL版本迁移中如何处理全局变量_手动比对新旧配置文件
jvm·数据库·python
AKA__Zas3 分钟前
初识多线程(初初识)
java·服务器·开发语言·学习方法
LiAo_1996_Y3 分钟前
JavaScript中利用宏任务拆分阻塞任务的实操案例
jvm·数据库·python
qq_349317486 分钟前
如何在 Go 中安全高效地将 SSH 公钥复制到远程服务器
jvm·数据库·python
zhangrelay7 分钟前
三分钟云课实践速通--概率统计--python版
linux·开发语言·笔记·python·学习·ubuntu
龙腾AI白云10 分钟前
大模型部署资源不足?轻量化部署解决方案
python·数据挖掘
一晌小贪欢12 分钟前
《Python办公Excel处理》第二节:精通openpyxl,让Excel排版与读写自动化
python·自动化·excel
我不是立达刘宁宇12 分钟前
CORS(跨原产资源共享)靶场1
python·http
Xidaoapi13 分钟前
Python调用OpenAI API完整教程:从零到精通
python
张赐荣13 分钟前
深入详解在 Python 中用 ctypes 调用 Windows API 清空回收站
开发语言·windows·python