目录:

  1. 举个栗子
  2. 概念介绍
  3. 使用场景

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
}

```

  

最新文章

  1. Linux系统程序的运行级别
  2. 【C#】【MySQL】C# 查询数据库语句@Row:=@Row+1
  3. C语言简单实现sizeof功能代码
  4. C语言的左位移能不能超过8位?
  5. ActivityNotFoundException: No Activity found to handle Intent
  6. Thrift初探:简单实现C#通讯服务程序
  7. 一步一步学python(五) -条件 循环和其他语句
  8. Maven POM入门
  9. File类遍历目录及文件
  10. ECMAScript课程
  11. linux 新建用户、用户组 以及为新用户分配权限的基本操作
  12. MyBatis动态传入表名
  13. freepbx的SIP通话客户端X-lite Yate eyeBeam Linphone
  14. 【CQOI2014】数三角形
  15. Daily Scrum (2015/10/26)
  16. Asp.net Vnext 实现IView
  17. yarn的使用
  18. CentOS ACL
  19. Jenkins安装与构建部署
  20. (43)C#网络1 http

热门文章

  1. django_day05
  2. C与C++有什么区别
  3. Helm安装ingress-nginx-4.2.3
  4. Java 多线程:基础
  5. logstash接受checkpoint防火墙日志并用ruby分词
  6. 回溯剪枝,dfs,bfs
  7. 依赖项安全检测新利器:Scorecard API
  8. 使用filebeat收集k8s上pod里的容器日志配置文件模板
  9. 初试 Prometheus + Grafana 监控系统搭建并监控 Mysql
  10. ​打造企业自己代码规范IDEA插件(上)