implemented singleton pattern
This commit is contained in:
		
							
								
								
									
										24
									
								
								creational/singleton/singleton.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										24
									
								
								creational/singleton/singleton.go
									
									
									
									
									
										Normal file
									
								
							@@ -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
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										29
									
								
								creational/singleton/singleton_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								creational/singleton/singleton_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -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)
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user