创建型第一个,使用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)
	}
}

  

输出:

最新文章

  1. [.net 面向对象程序设计进阶] (15) 缓存(Cache)(二) 利用缓存提升程序性能
  2. [linux] grep awk sort uniq学习
  3. NotORM(PHP的ORM框架)
  4. iOS 设计模式之抽象工厂
  5. SQL中存储过程的例子
  6. 表单javascript checkbox全选 反选 全不选
  7. mysql排行榜sql的实现
  8. java/php/c#版rsa签名以及验签实现
  9. android binder机制之——(创建binder服务)
  10. JS判断访问设备是移动设备还是pc
  11. HashMap面试题:90%的人回答不上来
  12. SQL优化 MySQL版 - 索引分类、创建方式、删除索引、查看索引、SQL性能问题
  13. Kali安装Docker
  14. vue + hbuilder 开发备忘录
  15. 利用 Charles Proxy 下载旧版本 iOS App
  16. 浅谈js的join()方法
  17. 【设计经验】1、Verilog中如何规范的处理inout信号
  18. VM虚拟机的配置文件(.vmx)损坏
  19. iOS开发安全 架构
  20. hdu 5761 Rower Bo 物理题

热门文章

  1. Asp.net Core3.0 跨域配置
  2. How to: Create a Business Model in the XPO Data Model Designer 如何:在 XPO 数据模型设计器中创建业务模型
  3. AoE 搭档 TensorFlow Lite ,让终端侧 AI 开发变得更加简单。
  4. Java EE 基本开发流程及数据库连接池 Druid
  5. Dynamics CRM中的地址知多D?
  6. Android框架式编程之LiveData
  7. 使用Visual Studio Code进行远程开发
  8. 1、netty入门说明
  9. vim简单操作命令
  10. 如何通过QT designer设置不让窗口最大化