设计模式:建造者模式

目录

一,概念

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

三,格式


一,概念

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

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

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

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

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

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

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

三,格式

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

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

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

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

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

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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值