Go实现常用软件设计模式一:单例模式
2024-10-20 21:11:15
目录:
- 举个栗子
- 概念介绍
- 使用场景
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
}
```
最新文章
- Linux系统程序的运行级别
- 【C#】【MySQL】C# 查询数据库语句@Row:=@Row+1
- C语言简单实现sizeof功能代码
- C语言的左位移能不能超过8位?
- ActivityNotFoundException: No Activity found to handle Intent
- Thrift初探:简单实现C#通讯服务程序
- 一步一步学python(五) -条件 循环和其他语句
- Maven POM入门
- File类遍历目录及文件
- ECMAScript课程
- linux 新建用户、用户组 以及为新用户分配权限的基本操作
- MyBatis动态传入表名
- freepbx的SIP通话客户端X-lite Yate eyeBeam Linphone
- 【CQOI2014】数三角形
- Daily Scrum (2015/10/26)
- Asp.net Vnext 实现IView
- yarn的使用
- CentOS ACL
- Jenkins安装与构建部署
- (43)C#网络1 http