Skip to content

Commit

Permalink
Added Singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
vladimir2217 committed Feb 7, 2025
1 parent a794c68 commit 1cccb55
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
28 changes: 28 additions & 0 deletions Misc/Initialization.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package Misc

import "sync"

type Singleton[T any] struct {
once sync.Once
Val Nullable[T]
Init func() Result[T]
}

func NewSingleton[T any](f func() Result[T]) *Singleton[T] {
return &Singleton[T]{
Init: f,
Val: NewNullable[T](),
}
}

func (this *Singleton[T]) Get() Result[T] {
var err error
this.once.Do(func() {
if this.Val.IsNil {
newObj := this.Init()
this.Val.Value = newObj.Value
err = newObj.Err
}
})
return Result[T]{Value: this.Val.Value, Err: err}
}
19 changes: 19 additions & 0 deletions Tests/Misc/Initialization_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package Misc

import (
"github.com/RENCI/GoUtils/Misc"
"github.com/stretchr/testify/assert"
"testing"
)

func Test_Singleton(t *testing.T) {

r := 1
s := Misc.NewSingleton(func() Misc.Result[int] {
r += 1
return Misc.NewResult(r, nil)
})
res := s.Get()
res = s.Get()
assert.Equal(t, 2, res.Value)
}

0 comments on commit 1cccb55

Please sign in to comment.