Skip to content

Latest commit

 

History

History
63 lines (34 loc) · 2.54 KB

README.md

File metadata and controls

63 lines (34 loc) · 2.54 KB

Sintleton Pattern - Go

The Singleton pattern is a design pattern that restricts the instantiation of a class to a single instance, ensuring controlled access to that instance globally throughout an application.

We can check that using "Race Data Detector" from golang, it is "-race" parameter to check race detector, which helps identify data races in concurrent programs, for example if there are two or more goroutines acessing the same varibles concurrently. Data Race Detector

You can do that in two different ways:

Benefits

  • Controlled Access: Global point of access to the instance, ensuring that all parts of the application use the same instance

  • Lazy Initialization: The instane can be created only when it is needed

  • Reduced Memory Footprint: Only one instance exists, it saving memory

  • Simplified Code: Simplify the codebase and reduces the complexity of object creation

  • Thread Safety: When implemented for, it can be made thread-safe, preventing issues in multi-threaded environments

When to Use

  • Configuration Management: applications settings or configurations, ensure that all the app access same configuration instance

  • Logging: Ensure that all log messages are sent to the same log file or output stream, maintaining consistency and avoid conflicts

  • Database Connections: Single database connection pool, reducing overhead of creating multiple connections.

  • Resource Management: Manage shared resources, such as thread pools or caches, Singleton ensure that all components interact with same resource manager

  • Event Handling: sometimes a single event manager is nedded to hanle events across different parts of the application, it can be centralized using Singleton

  • Service Locators: If you are implementing a service locator pattern, using a Singleton to manage service instances can streamline access to those services

How to execute

go run -race golang-singleton-once.go

and

go run -race golang-singleton-unsafe.go

Diagram

alt text

Sequence diagram

alt text

Architecture