php editor Apple is here to introduce to you a commonly used design pattern - the design pattern with a singleton. In software development, the singleton pattern is widely used, which ensures that a class has only one instance and provides a global access point. This design pattern can improve code reusability and performance, while also avoiding some potential problems. When using this design pattern, you need to pay attention to details such as thread safety and lazy loading to ensure the correctness and reliability of the implementation.
I am still not a golang expert and trying to understand and learn best practices
How to initialize a singleton in a package and make it thread-safe so that even if the package is imported multiple times in different files, there will only be one instance
Now the instance sessions
is started in main, but then I have to pass it. How do I start an instance of sessions
inside the sess
package and make it a global variable or something else inside the package?
I hope it is a private variable within the sess
package
package main func main(){ sessions := sess.Init() }
sess
module
package sess import ( "sync" "time" ) type pool struct { lock sync.RWMutex sessions map[string]*session } func Init() *pool { p := &pool{ sessions: map[string]*session{}, } return p } func (p *pool) Set(sid string, s *session){ p.lock.Lock() defer p.lock.Unlock() p.sessions[sid] = s } func (p *pool) Get(sid string) (*session, bool){ p.lock.RLock() defer p.lock.RUnlock() s, ok := p.sessions[sid] return s, ok }
Use a singleton to declare and initialize the exported package-level variables. There is an initialization instance for each package-level variable, rather than an instance or initialization for each import.
package sess import ( "sync" "time" ) type pool struct { lock sync.RWMutex sessions map[string]*session } var Pool = &pool{sessions: map[string]*session{}} func (p *pool) Set(sid string, s *session){ p.lock.Lock() defer p.lock.Unlock() p.sessions[sid] = s } func (p *pool) Get(sid string) (*session, bool){ p.lock.RLock() defer p.lock.RUnlock() s, ok := p.sessions[sid] return s, ok }
The above is the detailed content of Design pattern with singleton in package. For more information, please follow other related articles on the PHP Chinese website!