Skip to content

Creational & Structural Patterns in Go

Idiomatic Go implementations of Thread-Safe Singletons, Factories, and Adapters.

1. Thread-Safe Singleton with sync.Once

In Go, the idiomatic way to ensure single instance creation is sync.Once:

package singleton

import "sync"

// ThreadSafeSingleton implements thread-safe singleton pattern
type ThreadSafeSingleton struct{}

var (
    threadSafeInstance *ThreadSafeSingleton
    mu                 sync.Mutex
)

// GetThreadSafeInstance returns the singleton instance
func GetThreadSafeInstance() *ThreadSafeSingleton {
    mu.Lock()
    defer mu.Unlock()

    if threadSafeInstance == nil {
        threadSafeInstance = &ThreadSafeSingleton{}
    }
    return threadSafeInstance
}

2. Notification Factory

package factory

// SimpleNotificationFactory creates different types of notifications
type SimpleNotificationFactory struct{}

// NewSimpleNotificationFactory creates a new SimpleNotificationFactory instance
func NewSimpleNotificationFactory() *SimpleNotificationFactory {
    return &SimpleNotificationFactory{}
}

// CreateNotification creates a notification based on the type
func (f *SimpleNotificationFactory) CreateNotification(notificationType string) (Notification, error) {
    switch notificationType {
    case "EMAIL":
        return NewEmailNotification(), nil
    case "SMS":
        return NewSMSNotification(), nil
    case "PUSH":
        return NewPushNotification(), nil
    default:
        return nil, fmt.Errorf("unknown notification type: %s", notificationType)
    }
}