Golang and design pattern-Singleton singleton pattern

The singleton pattern is one of the longest-used design patterns in our work, and the singleton pattern is also a creational design pattern.

This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its only object, directly, without instantiating an object of this class.

The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to be accessed by the outside world, so as to facilitate the control of the number of instances and save system resources.

The singleton mode is generally divided into two implementation methods: the lazy man mode and the hungry man mode

hungry man mode

Indicates that an instance of the program has been created during the initialization phase or before use, and will not be created in the subsequent life cycle of the program

// 声明一个结构体
type IPhone struct {
	Version int
}

// 用来存储IPhone的实例
var iphone *IPhone

// init函数保证了GetInstance()被调用前完成对象初始化 或可以直接 var iphone  = &IPhone{}
func init() {
	iphone = &IPhone{Version: 7}
	// 输出iphoen对象指针地址
	fmt.Printf("初始化iphone指针:%p \n", iphone)
}

// 获取IPhone的实例
func GetInstance() *IPhone {
	return iphone
}

test

func main() {
	// 第一次获取实例
	iphone1 := GetInstance()
	// 验证获取到了实例
	fmt.Printf("这是IPhone%v \n", iphone1.Version)

	// 第二次获取实例
	iphone2 := GetInstance()

	//输出两次实例的指针地址,判断是否是同一个对象
	fmt.Printf("iphone1指针:%p \n", iphone1)
	fmt.Printf("iphone2指针:%p", iphone2)
}

operation result

It can be seen that our instance is obtained successfully, and its Version field is output. Compared with the three pointer addresses, all of them are the same, indicating that the same instance is obtained through the GetInstance() method

lazy mode

The lazy man mode, as the name implies, is lazy. It does not instantiate when there is no object that needs to be called, and instantiates the object when someone comes to it to ask for an object.

import (
	"fmt"
	"sync"
)

type IPhone struct {
	Version int
}

// 用来存储IPhone的实例
var iphone *IPhone

// once.Do可以保证函数只可能执行一次,防止高并发场景下多次执行实例化方法
var once sync.Once

func GetInstance() *IPhone {
	if iphone == nil {
		once.Do(func() {
			iphone = &IPhone{Version: 13}
			// 输出iphoen对象指针地址
			fmt.Printf("初始化iphone指针:%p \n", iphone)
		})
	}

	return iphone
}

test

The test can use the same code above. Let's see the result directly

The results are in line with our expectations

 

The code has been uploaded to Github: LyonNee/design_patterns_with_go: Golang-based design pattern code (github.com) 

Guess you like

Origin blog.csdn.net/Lyon_Nee/article/details/119578090