Golang 单例模式 singleton pattern
在Java中,单例模式的实现主要依靠类中的静态字段。在Go语言中,没有静态类成员,所以我们使用的包访问机制和函数来提供类似的功能。来看下下面的例子:
package singleton
import (
"fmt"
)
type Singleton interface {
SaySomething()
}
type singleton struct {
text string
}
var oneSingleton Singleton
func NewSingleton(text string) Singleton {
if oneSingleton == nil {
oneSingleton = &singleton{
text: text,
}
}
return oneSingleton
}
func (this *singleton) SaySomething() {
fmt.Println(this.text)
}
来测试下:
package main
import (
"Hello/singleton"
)
func main() {
mSingleton, nSingleton := singleton.NewSingleton("hello"), singleton.NewSingleton("hi")
mSingleton.SaySomething()
nSingleton.SaySomething()
}
输出结果:
相关阅读:
Golang通过Thrift框架完美实现跨语言调用 http://www.linuxidc.com/Linux/2013-09/90748.htm
golang里如何将一个struct指针转换成slice http://www.linuxidc.com/Linux/2013-04/83106.htm
Ubuntu 安装Go语言包 http://www.linuxidc.com/Linux/2013-05/85171.htm
《Go语言编程》高清完整版电子书 http://www.linuxidc.com/Linux/2013-05/84709.htm
Go语言并行之美 -- 超越 “Hello World” http://www.linuxidc.com/Linux/2013-05/83697.htm
我为什么喜欢Go语言 http://www.linuxidc.com/Linux/2013-05/84060.htm
最新文章
- 10月28日PHP基础知识测试题
- Linux学习 :字符设备框架
- JAVA6开发WebService (二)——JAX-WS例子
- matlab算法
- m3u8文件简介
- Android webview中cookie增加/修改
- windows server作为文件服务器如何精细控制权限
- Delphi ADOQuery连接数据库的查询、插入、删除、修改
- ELK-初识Elasticsearch
- AOP in dotnet :AspectCore的参数拦截支持
- luogu P5302 [GXOI/GZOI2019]特技飞行
- 五一之起一台服务器玩玩-u盘安装centos
- Spring事务事件监控
- Linux 网络编程 入门-常用函数
- (摘录)String是值传递还是引用传递
- ES6-字符串扩展-padStart(),padEnd()
- MYSQL一次千万级连表查询优化
- centos7 安装遇到的问题
- jquery.validate remote 和 自定义验证方法
- 小程序 组件 Component