検索
ホームページバックエンド開発GolangGo デザイン パターン #Singleton

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.

以上がGo デザイン パターン #Singletonの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Debian OpenSSLの脆弱性は何ですかDebian OpenSSLの脆弱性は何ですかApr 02, 2025 am 07:30 AM

OpenSSLは、安全な通信で広く使用されているオープンソースライブラリとして、暗号化アルゴリズム、キー、証明書管理機能を提供します。ただし、その歴史的バージョンにはいくつかの既知のセキュリティの脆弱性があり、その一部は非常に有害です。この記事では、Debian SystemsのOpenSSLの共通の脆弱性と対応測定に焦点を当てます。 Debianopensslの既知の脆弱性:OpenSSLは、次のようないくつかの深刻な脆弱性を経験しています。攻撃者は、この脆弱性を、暗号化キーなどを含む、サーバー上の不正な読み取りの敏感な情報に使用できます。

PPROFツールを使用してGOパフォーマンスを分析しますか?PPROFツールを使用してGOパフォーマンスを分析しますか?Mar 21, 2025 pm 06:37 PM

この記事では、プロファイリングの有効化、データの収集、CPUやメモリの問題などの一般的なボトルネックの識別など、GOパフォーマンスを分析するためにPPROFツールを使用する方法について説明します。

Goでユニットテストをどのように書きますか?Goでユニットテストをどのように書きますか?Mar 21, 2025 pm 06:34 PM

この記事では、GOでユニットテストを書くことで、ベストプラクティス、モッキングテクニック、効率的なテスト管理のためのツールについて説明します。

GOでテスト用のモックオブジェクトとスタブを書くにはどうすればよいですか?GOでテスト用のモックオブジェクトとスタブを書くにはどうすればよいですか?Mar 10, 2025 pm 05:38 PM

この記事では、ユニットテストのためにGOのモックとスタブを作成することを示しています。 インターフェイスの使用を強調し、模擬実装の例を提供し、模擬フォーカスを維持し、アサーションライブラリを使用するなどのベストプラクティスについて説明します。 articl

GOのジェネリックのカスタムタイプ制約を定義するにはどうすればよいですか?GOのジェネリックのカスタムタイプ制約を定義するにはどうすればよいですか?Mar 10, 2025 pm 03:20 PM

この記事では、GENICSのGOのカスタムタイプの制約について説明します。 インターフェイスがジェネリック関数の最小タイプ要件をどのように定義するかを詳しく説明し、タイプの安全性とコードの再利用性を改善します。 この記事では、制限とベストプラクティスについても説明しています

Goの反射パッケージの目的を説明してください。いつリフレクションを使用しますか?パフォーマンスへの影響は何ですか?Goの反射パッケージの目的を説明してください。いつリフレクションを使用しますか?パフォーマンスへの影響は何ですか?Mar 25, 2025 am 11:17 AM

この記事では、コードのランタイム操作に使用されるGoの反射パッケージについて説明します。シリアル化、一般的なプログラミングなどに有益です。実行やメモリの使用量の増加、賢明な使用と最高のアドバイスなどのパフォーマンスコストについて警告します

トレースツールを使用して、GOアプリケーションの実行フローを理解するにはどうすればよいですか?トレースツールを使用して、GOアプリケーションの実行フローを理解するにはどうすればよいですか?Mar 10, 2025 pm 05:36 PM

この記事では、トレースツールを使用してGOアプリケーションの実行フローを分析します。 手動および自動計装技術について説明し、Jaeger、Zipkin、Opentelemetryなどのツールを比較し、効果的なデータの視覚化を強調しています

GOでテーブル駆動型テストをどのように使用しますか?GOでテーブル駆動型テストをどのように使用しますか?Mar 21, 2025 pm 06:35 PM

この記事では、GOでテーブル駆動型のテストを使用して説明します。これは、テストのテーブルを使用して複数の入力と結果を持つ関数をテストする方法です。読みやすさの向上、重複の減少、スケーラビリティ、一貫性、および

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。