go设计模式--单例singleton
2024-09-05 19:09:58
创建型第一个,使用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) } }
输出:
最新文章
- [.net 面向对象程序设计进阶] (15) 缓存(Cache)(二) 利用缓存提升程序性能
- [linux] grep awk sort uniq学习
- NotORM(PHP的ORM框架)
- iOS 设计模式之抽象工厂
- SQL中存储过程的例子
- 表单javascript checkbox全选 反选 全不选
- mysql排行榜sql的实现
- java/php/c#版rsa签名以及验签实现
- android binder机制之——(创建binder服务)
- JS判断访问设备是移动设备还是pc
- HashMap面试题:90%的人回答不上来
- SQL优化 MySQL版 - 索引分类、创建方式、删除索引、查看索引、SQL性能问题
- Kali安装Docker
- vue + hbuilder 开发备忘录
- 利用 Charles Proxy 下载旧版本 iOS App
- 浅谈js的join()方法
- 【设计经验】1、Verilog中如何规范的处理inout信号
- VM虚拟机的配置文件(.vmx)损坏
- iOS开发安全 架构
- hdu 5761 Rower Bo 物理题
热门文章
- Asp.net Core3.0 跨域配置
- How to: Create a Business Model in the XPO Data Model Designer 如何:在 XPO 数据模型设计器中创建业务模型
- AoE 搭档 TensorFlow Lite ,让终端侧 AI 开发变得更加简单。
- Java EE 基本开发流程及数据库连接池 Druid
- Dynamics CRM中的地址知多D?
- Android框架式编程之LiveData
- 使用Visual Studio Code进行远程开发
- 1、netty入门说明
- vim简单操作命令
- 如何通过QT designer设置不让窗口最大化