Skip to content

Instantly share code, notes, and snippets.

@houming818
Created February 18, 2014 13:23
Show Gist options
  • Save houming818/9070884 to your computer and use it in GitHub Desktop.
Save houming818/9070884 to your computer and use it in GitHub Desktop.
golang中单例模式。
package crawler
import (
"log"
)
type Url string
type Body string
type MemStore struct {
key string
datas map[Url]Body
}
type FileName string
type FileStore struct {
key string
datas map[Url]FileName
}
type storesRoot struct {
memStores map[string]*MemStore
fileStores map[string]*FileStore
}
// 单利模仿javascript 原型链
var storesroot *storesRoot
func GetMemStore(key string) *MemStore {
tmp := stores("MemStores")(key)
ret, ok := tmp.(*MemStore)
if ok {
return ret
} else {
log.Fatalln("Unkown MemStore ", key)
return nil
}
}
func GetFileStore(key string) *FileStore {
tmp := stores("FileStores")(key)
store, ok := tmp.(*FileStore)
if ok {
return store
} else {
log.Fatalln("Unkown FileStore ", key)
return nil
}
}
func stores(storeType string) func(key string) (ret interface{}) {
if storesroot == nil {
storesroot = new(storesRoot)
}
instance := storesroot
if instance.memStores == nil || instance.fileStores == nil {
instance.memStores = make(map[string]*MemStore)
instance.fileStores = make(map[string]*FileStore)
}
return func(key string) interface{} {
switch storeType {
case "FileStores":
ret, exist := instance.fileStores[key]
if !exist {
v := newFileStore(key)
instance.fileStores[key] = v
return v
} else {
return ret
}
case "MemStores":
ret, exist := instance.memStores[key]
if !exist {
v := newMemStore(key)
instance.memStores[key] = v
return v
} else {
return ret
}
default:
log.Fatalln("Unkown Store Type")
return nil
}
}
}
func newFileStore(key string) *FileStore {
ret := new(FileStore)
ret.key = key
ret.datas = make(map[Url]FileName)
return ret
}
func newMemStore(key string) *MemStore {
ret := new(MemStore)
ret.key = key
ret.datas = make(map[Url]Body)
return ret
}
func (store *MemStore) Set(key Url, value Body) error {
store.datas[key] = value
return nil
}
func (store *MemStore) Get(key Url) Body {
return store.datas[key]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment