美文网首页
Golang单例模式(非线程安全)

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

作者: FredricZhu | 来源:发表于2019-06-18 16:36 被阅读0次

    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)
        }
    }
    

    程序输出如下,


    image.png

    相关文章

      网友评论

          本文标题:Golang单例模式(非线程安全)

          本文链接:https://www.haomeiwen.com/subject/eczfqctx.html