Home  >  Article  >  Backend Development  >  Design pattern with singleton in package

Design pattern with singleton in package

WBOY
WBOYforward
2024-02-15 15:33:081095browse

Design pattern with singleton in package

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.

Question content

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()
}

sessmodule

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
}

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete