Skip to content

Instantly share code, notes, and snippets.

@Clivern
Created September 3, 2021 21:51
Show Gist options
  • Save Clivern/f33419f1fc7896d057208828432925a2 to your computer and use it in GitHub Desktop.
Save Clivern/f33419f1fc7896d057208828432925a2 to your computer and use it in GitHub Desktop.
Singleton Pattern Connection Pool
package main
import (
"fmt"
"sync"
)
// DB type
type DB struct{}
func (s *DB) name() string {
return "Joe Doe"
}
// ConnectionPool type
type ConnectionPool struct {
sync.RWMutex
items map[string]interface{}
}
// NewConnectionPool creates a new instance of ConnectionPool
func NewConnectionPool() ConnectionPool {
return ConnectionPool{items: make(map[string]interface{})}
}
// Get a key from a concurrent map
func (c *ConnectionPool) Get(key string) (interface{}, bool) {
c.Lock()
defer c.Unlock()
value, ok := c.items[key]
return value, ok
}
// Set a key in a concurrent map
func (c *ConnectionPool) Set(key string, value interface{}) {
c.Lock()
defer c.Unlock()
c.items[key] = value
}
// Remove removes a key
func (c *ConnectionPool) Remove(key string) {
c.Lock()
defer c.Unlock()
delete(c.items, key)
}
var cp ConnectionPool
func init() {
cp = NewConnectionPool()
}
func main() {
if _, ok := cp.Get("db"); !ok {
cp.Set("db", &DB{})
}
v, _ := cp.Get("db")
fmt.Println(v.(*DB).name())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment