go设计模式--单例singleton

创建型第一个,使用TDD作的。

singleton.go

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
}

  

singleton_test.go

package singleton

import "testing"

func TestGetInstance(t *testing.T) {
	counter1 := GetInstance()

	if counter1 == nil {
		t.Error("expected pointer to Singleton after calling GetInstance(), not nil")
	}
	expectedCounter := counter1
	currentCount := counter1.AddOne()

	if currentCount != 1 {
		t.Errorf("After calling for the first time to count, the count must be 1 but it is %d\n", currentCount)
	}

	counter2 := GetInstance()

	if counter2 != expectedCounter {
		t.Error("Expected same instance in counter2, but it go a different instance.")
	}

	currentCount = counter2.AddOne()
	if currentCount != 2 {
		t.Errorf("After calling AddOne using the second counter, the current count must be 2 but was %d\n", currentCount)
	}
}

  

输出:

猜你喜欢

转载自www.cnblogs.com/aguncn/p/11832147.html
今日推荐