This blog we continue to look at design patterns, today brings a simplest and most commonly used mode-a singleton mode . So what is a singleton pattern? I believe we are most familiar with it, so let's get a quick look at its definition.
Ensure that a class has only one instance and provides a global access point to access it.
This explanation is simple enough. It's plain to say that if we want us to have only 1 or 0 instances of that class in our system. Although the singleton mode is very simple, but the familiar Java classmate May understand, the singleton pattern has many writing,,, ... 懒汉式 饿汉式 双重锁 What is the purpose of so many forms? True, but their purpose is clear, is to ensure that in a particular case of the singleton- 并发 .
OK, now that we understand the singleton pattern, let's start by describing the singleton pattern in code. The first is the simplest single case, where we do not consider concurrency .
package managerimport ( "fmt")var m *Managerfunc GetInstance() *Manager { ifnil { m = &Manager {} } return m}typestruct {}func (p Manager) Manage() { fmt.Println("manage...")}
This is one of the simplest singleton, for the Manager struct, we provide a GetInstance function to get its instance, this function first to determine whether the M variable is empty, if it is empty to assign a value Manager of a pointer type, a small judgment, it is guaranteed that we in the second call , instead of GetInstance re Manager -acquiring the instance, the only instance is guaranteed.
The above code is really simple, but also implemented the simplest singleton mode, but do you have to consider the concurrency of this point, in the case of concurrency, this is still working properly? Come on, take a walk with the following ideas and see where the problem appears.
Now we are going to call the function in the concurrency situation, and GetInstance now just before the first goroutine executes to m = &Manager {} this sentence, the second goroutine also to get the instance, the second goroutine to determine if M is nil, because m = &Manager{} There is no time to execute, so M is definitely nil, now the problem is that if the statement may be executed two times!
In the case described above, because it m = &Manager{} may be executed several times, so we write a single case is invalid, this time we should consider to our single-case lock.
At this point we need to introduce the lock mechanism of go-- sync.Mutex and modify our code,
package Managerimport ( "sync" "FMT" ) var m *managervar lock *sync. Mutex = &sync. Mutex {}func getinstance () *manager {lock. Lock () defer lock. Unlock () if m = = nil {m = &manager {} } return m}type Manager struct {}func (P Manager) Manage () {fmt. Println ( "Manage ..." )}
The
Code has made a simple modification, introduced a lock mechanism, in the getinstance function, each call we will be a lock to ensure that only one goroutine execute it, this time the concurrency problem is resolved. But now no matter what the situation will be a lock, and the cost of locking is very large, there is no way to continue to further optimize our code? Students familiar with Java may have thought of the dual concept, yes, in go we can also use the double lock mechanism to improve efficiency.
package Managerimport ( "sync" "FMT" ) var m *managervar lock *sync. Mutex = &sync. Mutex {}func getinstance () *manager {if m = =
nil {lock. Lock ()
defer lock. Unlock ()
if m = =
nil {m = &man Ager {}}}
return m}
type Manager
struct {}
func (P Manager) Manage () {fmt. Println (
"Manage ..." )}
The code is only slightly modified, but we used two judgments, and we put the synchronization lock after the conditional judgment, which avoids the lock every call, improve the efficiency of code execution.
This is a perfect example of a single code, but it's not over yet, and in go we have a more elegant way to do it. What is the purpose of the singleton? Ensure that the instantiated code executes only once, and in go there is such a mechanism to ensure that the code executes only once and does not require us to manually lock and unlock. Yes, that's ours sync.Once , and it has a Do method, in which the function go will only guarantee the call only once! Modify our code again,
package managerimport ( "sync" "fmt")var m *Managervar once sync.Oncefunc GetInstance() *Manager { once.Do(func() { m = &Manager {} }) return m}typestruct {}func (p Manager) Manage() { fmt.Println("manage...")}
The code was simpler, and there was no discovery--pretty! The parameter of the Once.do method is a function, here we give an anonymous function, in this function we do the work is very simple, is to assign the value m variable, and go can ensure that the code in this function is only executed once!
OK, to the present singleton mode we are finished, the content is not much, because the singleton mode is too simple and too common. We use a singleton to ensure that there is only one instance of the entire system, and we lock it in order to keep it handy in a concurrent environment. However, although simple, we can not be willful use, because this practice has been in memory, some of the things we use is not so frequent use of a single case is not the result of the waste of memory? Everyone in the use of a single case or to think more, this module is not suitable for a single case!
Design mode-Singleton mode (Go language description)