1
0
Fork 0
design-patterns/go/singleton/main.go

45 lines
1000 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
/*
实例
汤宝宝混穿到了泰拉世界,并成为了泰拉联邦的唯一统治者。人类只有一个帝皇!
*/
import (
"fmt"
"sync"
)
// 帝皇类
type Emperor struct {
Name string
}
var emperorInstance *Emperor
var once sync.Once
// 获取帝皇实例的函数
func GetEmperorInstance(name string, announce string) *Emperor {
fmt.Println(announce)
once.Do(func() {
emperorInstance = &Emperor{Name: name}
})
return emperorInstance
}
func main() {
fmt.Println("========= 单例模式 =========")
// 获取帝皇实例
emperor1 := GetEmperorInstance("汤宝宝", "泰拉联邦的帝皇诞生了!")
fmt.Printf("帝皇的名字是:%s\n", emperor1.Name)
emperor2 := GetEmperorInstance("王二狗", "泰拉联邦的帝皇又一次诞生了!")
fmt.Printf("帝皇的名字是:%s\n", emperor2.Name)
if emperor1 == emperor2 {
fmt.Printf("泰拉只有一个帝皇:%s\n\n", emperor1.Name)
}
fmt.Println("======= 单例模式结束 =======")
}