歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Golang 單例模式 singleton pattern

Golang 單例模式 singleton pattern

日期:2017/3/1 9:48:53   编辑:Linux編程

在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()
}

輸出結果:

Copyright © Linux教程網 All Rights Reserved