目录:
- 举个栗子
概念介绍
使用场景
1.举个栗子
类图
plantuml
```
@startuml
'https://plantuml.com/class-diagram
class Elephant {
String name
String getName();
}
class Refrigerator {
List <Elephant> elephants;
void add(Elephant elephants);
}
class Main {
void main()
}
@enduml
```
按类图实现基本需求
2.概念解释
单例模式:全局唯一的对象
3.使用场景
main.go
```
package main
import (
"dbTest/Builder/singleton/elephant"
"dbTest/Builder/singleton/refrigerator"
"dbTest/Builder/singleton/refrigeratorCounter"
"fmt"
"time"
)
func main() {
fmt.Println("start add elephant")
elephants := elephant.Elephant{
"rampage",
}
refrigeratorEntity := refrigerator.GetInstance()
refrigeratorEntity.AddElephant(elephants)
refrigeratorCount := refrigeratorCounter.RefrigeratorCounter{}
for i := 0; i < 10; i++ {
go refrigeratorCount.CounterNum()
}
time.Sleep(time.Second)
fmt.Println("we are finished, nums:",refrigeratorEntity.GetTotalNum())
}
```
elephant.go
```
package elephant
type Elephant struct {
Name string
}
func (e Elephant) getName() string {
return e.Name
}
```
refigerator.go
```
package refrigerator
import (
"dbTest/Builder/singleton/elephant"
"sync"
)
var once = sync.Once{}
// 1、设计为小写字母开头,表示只在refrigerator包内可见,限制客户端程序的实例化
type refrigerator struct {
elephants []elephant.Elephant
}
// 2、定义一个包内可见的实例对象,也即单例
// 懒汉模式,先只声明,用的时候再初始化,有非并发安全,所有用sync.Once加锁
var instance *refrigerator
// 饿汉模式,系统初始化期间就完成了单例对象的实例化
// var instance = &refrigerator{elephants: []elephant.Elephant{}}
// GetInstance
// 3、定义一个全局可见的唯一访问方法
func GetInstance() *refrigerator {
once.Do(func() {
instance = &refrigerator{elephants: []elephant.Elephant{}}
})
return instance
}
func (r *refrigerator) AddElephant(elephants elephant.Elephant) {
r.elephants = append(r.elephants, elephants)
}
func (r refrigerator) GetTotalNum() int {
return len(r.elephants)
}
```
refrigeratorCounter.go
```
package refrigeratorCounter
import (
"dbTest/Builder/singleton/refrigerator"
"fmt"
)
type RefrigeratorCounter struct {
}
func (rc RefrigeratorCounter) CounterNum() {
fmt.Println("refrigeratorCount:",refrigerator.GetInstance().GetTotalNum())
return
}
```