singleton

package
v0.0.0-...-bcea9b7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2021 License: MIT Imports: 2 Imported by: 0

README

Usage

the singleton pattern is a software design pattern that restricts the instantiation of a type to one object

Example

package main 

import (
	"github.com/donutloop/toolkit/singleton"
)

type config struct {
	Addr string
	Port int
}

var configSingleton singleton.NewSingleton = singleton.NewSingleton(func() (interface{}, error) {
	return &config{Addr:"localhost", Port:80}, nil
})

func Config() (*config, error) {
	s, err := configSingleton.Get()
	if err != nil {
		return nil, err
	}
	return s.(*config), nil
}

func main() {
	config, err := Config()
	// do things 
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConstructorFunc

type ConstructorFunc func() (interface{}, error)

type Singleton

type Singleton interface {
	Get() (interface{}, error)
	Reset()
}
Example
package main

import (
	"fmt"

	"github.com/donutloop/toolkit/singleton"
)

func main() {
	type config struct {
		Addr string
		Port int
	}

	configSingleton := singleton.NewSingleton(func() (interface{}, error) {
		return &config{Addr: "localhost", Port: 80}, nil
	})

	configFunc := func() (*config, error) {
		s, err := configSingleton.Get()
		if err != nil {
			return nil, err
		}

		return s.(*config), nil
	}

	c, err := configFunc()
	if err != nil {
		fmt.Printf("error: (%v) \n", err)
	}

	fmt.Printf("%#v \n", c)
}
Output:

&singleton_test.config{Addr:"localhost", Port:80}

func NewSingleton

func NewSingleton(constructor ConstructorFunc) Singleton

Call to create a new singleton that is instantiated with the given constructor function. Constructor is not called until the first call of Get(). If constructor returns a error, it will be called again on the next call of Get().

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL