mohuishou / go-design-pattern

golang design pattern go 设计模式实现,包含 23 种常见的设计模式实现,同时这也是极客时间-设计模式之美 的笔记
https://lailin.xyz/post/go-design-pattern.html
2.04k stars 339 forks source link

单例本身没有问题,但是你代码中 singleton 的申明是需要加上字段的;另外 assert.Equal 直接调用也是有问题的,不会判断地址值而是判断的对象值。参考:[https://github.com/stretchr/testify/issues/1076](https://github.com/stretchr/testify/issues/1076) #12

Closed mohuishou closed 1 year ago

mohuishou commented 1 year ago
          单例本身没有问题,但是你代码中 singleton 的申明是需要加上字段的;另外 assert.Equal 直接调用也是有问题的,不会判断地址值而是判断的对象值。参考:[https://github.com/stretchr/testify/issues/1076](https://github.com/stretchr/testify/issues/1076)

所以你的 singleton_test 并没有达到实际的测试效果,只是“负负得正”而已。一个正确的单测:

func TestGetInstance(t *testing.T) {
    s1 := GetInstance()
    s2 := GetInstance()
    s3 := GetLazyInstance()
    s4 := GetLazyInstance()
    assert.Equal(t, reflect.ValueOf(s1).Pointer(), reflect.ValueOf(s2).Pointer())
    assert.Equal(t, reflect.ValueOf(s3).Pointer(), reflect.ValueOf(s4).Pointer())
    assert.NotEqual(t, reflect.ValueOf(s2).Pointer(), reflect.ValueOf(s3).Pointer())
}

Originally posted by @xyling1024 in https://github.com/mohuishou/go-design-pattern/issues/2#issuecomment-1534680832