在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

最新文章

  1. 10月28日PHP基础知识测试题
  2. Linux学习 :字符设备框架
  3. JAVA6开发WebService (二)——JAX-WS例子
  4. matlab算法
  5. m3u8文件简介
  6. Android webview中cookie增加/修改
  7. windows server作为文件服务器如何精细控制权限
  8. Delphi ADOQuery连接数据库的查询、插入、删除、修改
  9. ELK-初识Elasticsearch
  10. AOP in dotnet :AspectCore的参数拦截支持
  11. luogu P5302 [GXOI/GZOI2019]特技飞行
  12. 五一之起一台服务器玩玩-u盘安装centos
  13. Spring事务事件监控
  14. Linux 网络编程 入门-常用函数
  15. (摘录)String是值传递还是引用传递
  16. ES6-字符串扩展-padStart(),padEnd()
  17. MYSQL一次千万级连表查询优化
  18. centos7 安装遇到的问题
  19. jquery.validate remote 和 自定义验证方法
  20. 小程序 组件 Component

热门文章

  1. USRP B210 更改A通道或B通道
  2. Systemd-journalctl日志管理
  3. JQuery 中each的使用方法
  4. 一些需要禁用的PHP危险函数(disable_functions)
  5. 题解 POJ1149 Pigs
  6. Jmeter+ant+Jenkins接口自动化框架搭建
  7. windows安装解压版postgresql
  8. maven的概念-01
  9. 用jstl的if或when标签判断字符串是否为空
  10. 博弈dp入门 POJ - 1678 HDU - 4597