Builder Pattern Usage in the Java API

The PubSub+ Java API uses the builder design pattern to create instances of messages, messaging services, publishers and receivers. Here's an example usage of the builder pattern to create a PubSub+ message:

/* Builder for creation of similarly configured messages */
final OutboundMessageBuilder messageBuilder = messagingService.messageBuilder();
final OutboundMessage message = messageBuilder
    .fromProperties(additionalProperties)    // For example TTL, Sender ID, Sequence Number etc.  
    .withExpiration(Instant.now()            // Sets expiration time using the current system time as starting point.
    .toEpochMilli() + 10000L)                // Expire the message in 10 seconds.
    .build("My_Message");                    // Builds the message.

The previous code clearly shows what each method is doing. This pattern also allows the creation of message objects with different numbers of parameters through methods that can be called in any order.

The diagram below illustrates the primary interfaces used by the PubSub+ Java API and how they are created with the builder pattern:

Illustration depicting the relationship between interfaces in Java API.

For more information about: