Golang单例模式(非线程安全)

singleton.go

// singleton.go
package singleton

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
}

func (s *singleton) GetCount() int {
    return s.count
}

singleton_test.go

// singleton_test
package singleton

import (
    "testing"
)

func TestGetInstance(t *testing.T) {
    counter1 := GetInstance()
    if counter1 == nil {
        t.Error("A new connectin object must have been made")
    }

    expectCounter := counter1

    currentCount := counter1.AddOne()
    if currentCount != 1 {
        t.Errorf("After called for the first time, the count value should be 1 but found: %v", currentCount)
    }

    counter2 := GetInstance()
    if counter2 != expectCounter {
        t.Error("Singleton instance must not be different")
    }

    currentCount = counter2.AddOne()
    if currentCount != 2 {
        t.Errorf("After calling twice of AddOne, currentCount should be 2 but found: %v", currentCount)
    }
}

程序输出如下,


Golang单例模式(非线程安全)_第1张图片
image.png

你可能感兴趣的:(Golang单例模式(非线程安全))