Skip to content

Commit 6638b3b

Browse files
committed
singleton improvements
1 parent 8d8c4dc commit 6638b3b

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

antipattern/singleton/singleton.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
package singleton
22

33
type singleton struct {
4-
calls int
4+
calls int
5+
creations int
56
}
67

78
var instance *singleton
89

910
func GetInstance() *singleton {
1011
if instance == nil {
1112
instance = new(singleton)
13+
instance.creations = 1
1214
}
1315
instance.calls++
1416
return instance
@@ -17,3 +19,7 @@ func GetInstance() *singleton {
1719
func (s *singleton) NumberOfCalls() int {
1820
return s.calls
1921
}
22+
23+
func (s *singleton) NumberOfCreations() int {
24+
return s.creations
25+
}

antipattern/singleton/singleton_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import "testing"
55
func TestGetInstance(t *testing.T) {
66
firstInstance := GetInstance()
77

8+
if firstInstance.NumberOfCreations() != 1 {
9+
t.Error("expected just one number of creations")
10+
}
11+
812
secondInstance := GetInstance()
913
if firstInstance != secondInstance {
1014
t.Error("expected same instance")
@@ -14,4 +18,8 @@ func TestGetInstance(t *testing.T) {
1418
if thirdInstance.NumberOfCalls() != 3 {
1519
t.Error("expected three calls")
1620
}
21+
22+
if firstInstance.NumberOfCreations() != 1 {
23+
t.Error("expected just one number of creations")
24+
}
1725
}

0 commit comments

Comments
 (0)