Go Design Patterns #Singleton
Design patterns are tried-and-tested solutions to common problems that arise in software design. They provide a template or guide for solving these problems in a flexible and reusable way.
Each pattern represents a best practice that developers can adapt to their specific context. Design patterns are often classified into three main categories.
To kickstart this series, let's talk about the Singleton pattern.
Singleton
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
This is useful in cases where you need to manage a shared resource, such as database connections or configuration settings.
Problem Statement
Often there is the need to ensure that only one instance of a class exists, such as when managing configurations or interacting with hardware resources. Without Singleton, creating multiple instances can lead to issues like inconsistent data or resource locks.
This is very common to happen when working with asynchronous code, where multiple goroutines can create new instances of a class or access shared resources.
Real-World Example
Consider a database connection pool: If multiple parts of your application create new connections at the same time, you may end up with redundant or conflicting database interactions. A Singleton ensures only one connection is created and used across the application.
Implementation
package main import ( "fmt" "sync" ) type Singleton interface { DoSomething() string } type singleton struct{} var lock = &sync.Mutex{} var instance *singleton func NewSingletonInstance() *singleton { if instance == nil { lock.Lock() defer lock.Unlock() if instance == nil { fmt.Println("Creating single instance now.") instance = &singleton{} } else { fmt.Println("Single instance already created.") } } else { fmt.Println("Single instance already created.") } return instance } func (s *singleton) DoSomething() string { return "Doing something." } func main() { instance1 := NewSingletonInstance() instance2 := NewSingletonInstance() fmt.Printf("%p\n", instance1) fmt.Printf("%p\n", instance2) }
The function NewSingletonInstance ensures that only one instance of singleton is created, even when called multiple times.
- First, it checks if instance is nil (i.e., no instance has been created yet).
- If instance is nil, it locks the section of code using lock.Lock() to prevent multiple goroutines from entering this section simultaneously.
- After locking, a second check is performed to ensure that no other goroutine created the instance between the first check and the time the lock was acquired.
- If instance is still nil, a new singleton instance is created and assigned to the global variable.
- The sync.Mutex and double-checked locking ensure that the creation of the singleton instance is thread-safe, preventing multiple goroutines from creating separate instances.
The above is the detailed content of Go Design Patterns #Singleton. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a
