Screenshot 2023-12-05 at 1.41.25 PM.png

Screenshot 2023-12-05 at 1.41.58 PM.png

Approach 1: Using Struct

Approach 2 : Using Interface

Sure, here is an example of how to use the Builder design pattern in Go to create a notification service:

package main

import (
    "fmt"
)

type Notification struct {
    message string
    recipient string
}

type NotificationBuilder interface {
    SetMessage(message string) (NotificationBuilder, error)
    SetRecipient(recipient string) (NotificationBuilder, error)
    Build() (Notification, error)
}

type EmailNotificationBuilder struct {
    notification Notification
}

func (b *EmailNotificationBuilder) SetMessage(message string) (NotificationBuilder, error) {
    if len(message) == 0 {
        return nil, fmt.Errorf("message cannot be empty")
    }

    b.notification.message = message
    return b, nil
}

func (b *EmailNotificationBuilder) SetRecipient(recipient string) (NotificationBuilder, error) {
    if len(recipient) == 0 {
        return nil, fmt.Errorf("recipient cannot be empty")
    }

    b.notification.recipient = recipient
    return b, nil
}

func (b *EmailNotificationBuilder) Build() (Notification, error) {
    if len(b.notification.message) == 0 || len(b.notification.recipient) == 0 {
        return Notification{},fmt.Errorf("notification is incomplete")
    }

    return b.notification, nil
}

func main() {
    emailBuilder := EmailNotificationBuilder{}

    emailBuilder.SetMessage("Hello, world!")

	emailBuilder.SetRecipient("[email protected]"); 

	emailNotification,err := emailBuilder.Build()

    if err != nil {
        fmt.Println("Error creating email notification:", err)
        return
    }

    fmt.Println("Email notification:", emailNotification)

     
}

In this example, the Notification struct represents a notification that can be sent to a recipient. The NotificationBuilder interface defines the methods that must be implemented by any struct that wants to build notifications. The EmailNotificationBuilder and SMSNotificationBuilder structs implement the NotificationBuilder interface and are used to build email and SMS notifications, respectively.

The main function shows how to use the Builder pattern to create notifications. The emailBuilder is used to create an email notification, and the smsBuilder is used to create an SMS notification.

The Builder pattern is a useful design pattern that can be used to create complex objects in a step-by-step manner. It can make code more readable and maintainable, and it can also reduce the amount of boilerplate code that needs to be written.