设计模式:建造者模式

目录

一,概念

二,不使用建造者有什么麻烦

三,格式


一,概念

建造者模式(Builder Pattern)是一种创建型设计模式,用于将复杂对象的构建与其表示分离,以便同样的构建过程可以创建不同的表示。建造者模式允许通过指定复杂对象的类型和内容逐步构造一个复杂对象,并允许它分步骤进行。

二,不使用建造者有什么麻烦

假设我们要自己开发一个Rabbitmq的客户端,在不同的工作模式下,对参数的传递有相应的要求,每一种模式都有不同的参数和参数的组合。

如果使用构造方法的方式,可以重载多种不同的参数组合,但是很难实现多种灵活组合。

如果使用set方式,这种可以达到灵活组合的目的,但是有两个问题,第一,必须提前设置mode,否则在判断的时候没办法校验。另外,set会让属性处于一个暴露的状态,而Rabbitmq客户端的性质是一个不可变对象,只要new出来之后,没必要set,set会破坏这种规则。

这个时候,建造者模式来了。

既能保证灵活组织参数,又不会让基本信息对外暴露。(属性放到内部类里面)

三,格式

1.目标类的构造方法要求传入Builder对象

2.Builder建造者位于目标类内部且用static描述

3.Builder建造者对外提供内置属性和方法,注意set返回的是Builder对象本身

4.Builder建造者提供build方法来实现对目标对象的创建

四,案例改造成建造者模式

java 复制代码
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitmqClient {
    private final ConnectionFactory factory;
    private Connection connection;
    private Channel channel;
    private final String exchange;
    private final String queue;
    private boolean durable;

    // 私有构造器,只能通过 Builder 类访问
    private RabbitmqClient(Builder builder) throws IOException, TimeoutException {
        this.factory = new ConnectionFactory();
        this.factory.setHost(builder.host);
        this.factory.setPort(builder.port);
        this.durable = builder.isDurable;
        this.exchange = builder.exchange;
        this.queue = builder.queue;

        // 创建新连接和通道
        this.connection = factory.newConnection();
        this.channel = connection.createChannel();

        // 声明持久的交换器
        channel.exchangeDeclare(exchange, "direct", durable);
        
        // 声明持久的队列,并设置排他、自动删除和绑定队列到交换器
        channel.queueDeclare(queue, durable, false, false, null);
        channel.queueBind(queue, exchange, "");
    }

    public void sendMsg(String routingKey, String msg) throws IOException {
        // 发送消息
        channel.basicPublish(exchange, routingKey, null, msg.getBytes("UTF-8"));
        System.out.println("Sent: " + msg);
    }

    // 资源清理
    public void close() throws IOException, TimeoutException {
        if (channel != null && channel.isOpen()) {
            channel.close();
        }
        if (connection != null && connection.isOpen()) {
            connection.close();
        }
    }

    // Builder 类
    public static class Builder {
        private String host = "localhost";
        private int port = 5672;
        private boolean isDurable = true;
        private String exchange;
        private String queue;

        public Builder setHost(String host) {
            this.host = host;
            return this;
        }

        public Builder setPort(int port) {
            this.port = port;
            return this;
        }

        public Builder setDurable(boolean durable) {
            isDurable = durable;
            return this;
        }

        public Builder setExchange(String exchange) {
            this.exchange = exchange;
            return this;
        }

        public Builder setQueue(String queue) {
            this.queue = queue;
            return this;
        }

        public RabbitmqClient build() throws IOException, TimeoutException {
            return new RabbitmqClient(this);
        }
    }
}

// 使用示例
class Client {
    public static void main(String[] args) throws IOException, TimeoutException {
        RabbitmqClient client = new RabbitmqClient.Builder()
                .setHost("localhost")
                .setPort(5672)
                .setDurable(true)
                .setExchange("myExchange")
                .setQueue("myQueue")
                .build();

        client.sendMsg("routingKey", "Hello, RabbitMQ!");

        // 记得在最后关闭资源
        client.close();
    }
}

在这个示例中,RabbitmqClient 类负责创建 RabbitMQ 连接和通道,并提供了发送消息的方法 sendMsgBuilder 内部类允许用户设置连接属性,如主机、端口、交换器和队列。

客户端代码使用 Builder 类来构建 RabbitmqClient 实例,然后调用 sendMsg 方法发送消息,并在操作完成后关闭资源。

请注意,这个示例代码假设 RabbitMQ 服务器正在运行,并且客户端有权限访问指定的交换器和队列。在生产环境中,还需要考虑异常处理、连接失败重试、消息确认、事务等高级特性。

相关推荐
笨手笨脚の3 小时前
设计模式-策略模式
设计模式·策略模式·行为型设计模式
王嘉俊9253 小时前
设计模式--适配器模式:优雅解决接口不兼容问题
java·设计模式·适配器模式
王嘉俊9253 小时前
设计模式--组合模式:统一处理树形结构的优雅设计
java·设计模式·组合模式
rongqing20193 小时前
Google 智能体设计模式:多智能体协作
设计模式
李广坤18 小时前
状态模式(State Pattern)
设计模式
李广坤20 小时前
观察者模式(Observer Pattern)
设计模式
李广坤20 小时前
中介者模式(Mediator Pattern)
设计模式
李广坤21 小时前
迭代器模式(Iterator Pattern)
设计模式
李广坤21 小时前
解释器模式(Interpreter Pattern)
设计模式
阿无,1 天前
java23种设计模式之前言
设计模式