Go实现单例模式

本文介绍了Go语言中如何实现单例模式,利用sync.Once的Do方法确保对象的唯一性,同时保证并发线程安全。通过测试验证,单例模式成功地创建了唯一实例并确保所有对象在同一内存地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

单例模式

实现原理

实现

测试


单例模式

单例模式是最简单的设计模式之一,它提供了创建对象的最佳方式。这种模式涉及到一个单一的结构体,该结构体负责创建自己的对象,同时确保只有单个对象被创建。即多次创建一个结构体的对象,得到的对象的存储地址永远与第一次创建对象的存储地址相同。

实现原理

利用 sync.Once 方法Do,确保Do中的方法只被执行一次的特性,创建单个结构体实例。

实现

import (
	"sync"
)

var (
	instance 	*School
	once 		sync.Once
)

type School struct {
	Name	string
	Tel		string
}

func CreateSchool(name, tel string) *School {
	once.Do(func() {
		instance = new(School)
		instance.Name = name
		instance.Tel = tel
	})
	
	return instance
}

使用Do方法也巧妙的保证了并发线程安全。

测试

package main

import (
	"fmt"
	"strconv"
	"sync"
)

var (
	instance 	*School
	once 		sync.Once
)

type School struct {
	Name	string
	Tel		string
}

func CreateSchool(name, tel string) *School {
	once.Do(func() {
		fmt.Println("----- init -----")
		instance = new(School)
		instance.Name = name
		instance.Tel = tel
	})

	return instance
}

func main() {
	var wg sync.WaitGroup
	wg.Add(10)
	for i:=0; i<10; i++ {
		go func(seq int) {
			defer wg.Done()
			seqStr := strconv.Itoa(seq)
			school := CreateSchool("school"+seqStr, seqStr)
			fmt.Printf(
				"%s\tname: %s,\t tel: %s,address:%p\n",
				seqStr,
				school.Name,
				school.Tel,
				school,
				)
		} (i)
	}

	wg.Wait()
}

执行结果:

----- init -----
9       name: school9,   tel: 9,address:0xc0000b0000
2       name: school9,   tel: 9,address:0xc0000b0000
5       name: school9,   tel: 9,address:0xc0000b0000
3       name: school9,   tel: 9,address:0xc0000b0000
4       name: school9,   tel: 9,address:0xc0000b0000
6       name: school9,   tel: 9,address:0xc0000b0000
0       name: school9,   tel: 9,address:0xc0000b0000
8       name: school9,   tel: 9,address:0xc0000b0000
7       name: school9,   tel: 9,address:0xc0000b0000
1       name: school9,   tel: 9,address:0xc0000b0000

可以看出,Do函数中的内容仅被执行了一次,所有实例化的对象都有相同的内容,且指向的地址相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值