diff --git a/.gitignore b/.gitignore index a1338d6..0b61b15 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,2 @@ # Binaries for programs and plugins *.exe -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ diff --git a/README.md b/README.md index a8e09e8..e6f0d57 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,8 @@ # golang-design-patterns Implementation of design patterns in Golang + + +### Table of contents +**[Creational Patterns](#creational-patterns)**
+**[Structural Patterns](#structural-patterns)**
+**[Behavioral Patterns](#behavioral-patterns)**
\ No newline at end of file diff --git a/creational/singleton/singleton.go b/creational/singleton/singleton.go new file mode 100644 index 0000000..52845af --- /dev/null +++ b/creational/singleton/singleton.go @@ -0,0 +1,24 @@ +package singleton + +type Singleton interface { + AddOne() int +} + +type singleton struct { + count int +} + +var instance *singleton + +func GetInstance() Singleton { + if instance == nil { + instance = new(singleton) + } + + return instance +} + +func (s *singleton) AddOne() int { + s.count++ + return s.count +} diff --git a/creational/singleton/singleton_test.go b/creational/singleton/singleton_test.go new file mode 100644 index 0000000..4e5b7df --- /dev/null +++ b/creational/singleton/singleton_test.go @@ -0,0 +1,29 @@ +package singleton + +import "testing" + +func TestGetInstance(t *testing.T) { + + firstCounter := GetInstance() + + if firstCounter == nil { + t.Error("Expected pointer to Singleton after calling GetInstance(), not nil") + } + + expectedCounter := firstCounter + + count := firstCounter.AddOne() + if count != 1 { + t.Errorf("After calling for the first time to count, the count must be 1 but it is %d\n", count) + } + + secondCounter := GetInstance() + if secondCounter != expectedCounter { + t.Error("Expected same counter in secondCounter but got different instance") + } + + count = secondCounter.AddOne() + if count != 2 { + t.Errorf("After calling AddOne in second counter, count must be 2 but was $d\n", count) + } +} \ No newline at end of file