English

Artykuł · Singleton · Fabryka abstrakcyjna

Singleton – jedna instancja i powody, by oddać ją kontenerowi DI

Singleton gwarantuje, że klasa ma dokładnie jedną instancję dostępną z całej aplikacji. Pokazujemy bezpieczne wątkowo implementacje w pięciu językach i wyjaśniamy, dlaczego dziś zwykle lepiej zarejestrować obiekt jako singleton w kontenerze DI.

Autor · · 9 min czytania

Singleton to najbardziej znany i zarazem najczęściej krytykowany wzorzec z katalogu GoF. Obiecuje dwie rzeczy: klasa ma dokładnie jedną instancję i istnieje globalny punkt dostępu do niej. Pierwsza bywa naprawdę potrzebna. Druga – o wiele rzadziej, niż się wydaje.

1
instancja na proces – nie na serwer ani na klaster
2
obietnice wzorca – jedna instancja i globalny dostęp
0
ukrytych zależności – tyle chcemy mieć po przejściu na DI

Problem: liczniki, które liczą do połowy

Sklep zbiera metryki – liczbę złożonych zamówień, nieudanych płatności, odpowiedzi z pamięci podręcznej. Rejestr liczników jest prostą klasą z mapą nazw na wartości. Problem pojawił się po kilku sprintach: wykres w panelu pokazywał o połowę mniej zamówień, niż było w bazie.

orders.ts / payments.ts
// orders.ts
const metrics = new MetricsRegistry();
metrics.increment("orders_placed");

// payments.ts – another module, another registry
const metrics = new MetricsRegistry();
metrics.increment("orders_placed"); // counted in a different map

Każdy moduł tworzył własny rejestr, a eksporter metryk czytał tylko jeden z nich. Potrzebujemy gwarancji, że w procesie istnieje jeden rejestr, i wygodnego sposobu, by każdy kod trafiał właśnie do niego.

Rozwiązanie: prywatny konstruktor i jeden punkt dostępu

Klasyczny Singleton zamyka konstruktor (nikt z zewnątrz nie zrobi new) i udostępnia statyczną właściwość albo metodę, która przy pierwszym wywołaniu tworzy instancję, a przy kolejnych zwraca tę samą.

Diagram: Struktura klasycznego Singletona
ElementPo co
prywatny konstruktorblokuje tworzenie kolejnych instancji przez new
statyczne pole z instancjąprzechowuje jedyny egzemplarz
statyczny punkt dostępuzwraca instancję, tworząc ją leniwie przy pierwszym użyciu
bezpieczeństwo wątkowedwa wątki naraz nie mogą utworzyć dwóch instancji

Implementacja w pięciu językach

Najczęstszy błąd w Singletonie to ręcznie pisane „sprawdź, czy null, i utwórz” bez synchronizacji – dwa wątki mogą wtedy jednocześnie zobaczyć null. Każdy z języków ma na to gotowe narzędzie: Lazy<T> w .NET, typ enum w Javie, sync.OnceValue w Go, a w Pythonie i TypeScripcie – sam system modułów.

MetricsRegistry

MetricsRegistry.cs
using System.Collections.Concurrent;

Parallel.For(0, 1000, _ => MetricsRegistry.Instance.Increment("hits"));
Console.WriteLine(MetricsRegistry.Instance.Get("hits")); // 1000

public sealed class MetricsRegistry
{
    // Lazy<T> is thread-safe by default (LazyThreadSafetyMode.ExecutionAndPublication).
    private static readonly Lazy<MetricsRegistry> LazyInstance = new(() => new MetricsRegistry());

    private readonly ConcurrentDictionary<string, long> _counters = new();

    private MetricsRegistry() => Console.WriteLine("Registry created once");

    public static MetricsRegistry Instance => LazyInstance.Value;

    public void Increment(string name) => _counters.AddOrUpdate(name, 1, (_, value) => value + 1);

    public long Get(string name) => _counters.GetValueOrDefault(name);
}
metrics-registry.ts
class MetricsRegistry {
  private static instance?: MetricsRegistry;
  private readonly counters = new Map<string, number>();

  private constructor() {
    console.log("Registry created once");
  }

  static getInstance(): MetricsRegistry {
    // JavaScript runs your code on a single thread, so no locking is needed.
    return (MetricsRegistry.instance ??= new MetricsRegistry());
  }

  increment(name: string): void {
    this.counters.set(name, (this.counters.get(name) ?? 0) + 1);
  }

  get(name: string): number {
    return this.counters.get(name) ?? 0;
  }
}

// Idiomatic alternative: a module is evaluated once, so its exports are shared.
export const metrics = MetricsRegistry.getInstance();

metrics.increment("hits");
MetricsRegistry.getInstance().increment("hits");
console.log(metrics.get("hits")); // 2
Metrics.java
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;

// An enum is the singleton recommended in Effective Java:
// thread-safe, and immune to serialization and reflection attacks.
enum MetricsRegistry {
    INSTANCE;

    private final ConcurrentHashMap<String, LongAdder> counters = new ConcurrentHashMap<>();

    public void increment(String name) {
        counters.computeIfAbsent(name, k -> new LongAdder()).increment();
    }

    public long get(String name) {
        LongAdder adder = counters.get(name);
        return adder == null ? 0 : adder.sum();
    }
}

public class Metrics {
    public static void main(String[] args) {
        IntStream.range(0, 1_000).parallel().forEach(i -> MetricsRegistry.INSTANCE.increment("hits"));
        System.out.println(MetricsRegistry.INSTANCE.get("hits")); // 1000
    }
}
metrics.go
package main

import (
	"fmt"
	"sync"
)

type MetricsRegistry struct {
	mu       sync.Mutex
	counters map[string]int64
}

// Default returns the process-wide registry. sync.OnceValue (Go 1.21+) runs the
// constructor exactly once, even when many goroutines call it at the same time.
var Default = sync.OnceValue(func() *MetricsRegistry {
	fmt.Println("registry created once")
	return &MetricsRegistry{counters: make(map[string]int64)}
})

func (r *MetricsRegistry) Inc(name string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.counters[name]++
}

func (r *MetricsRegistry) Get(name string) int64 {
	r.mu.Lock()
	defer r.mu.Unlock()
	return r.counters[name]
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			Default().Inc("hits")
		}()
	}
	wg.Wait()
	fmt.Println(Default().Get("hits")) // 1000
}
metrics.py
import threading
from collections import Counter
from concurrent.futures import ThreadPoolExecutor


class MetricsRegistry:
    def __init__(self) -> None:
        print("registry created once")
        self._lock = threading.Lock()
        self._counters: Counter[str] = Counter()

    def inc(self, name: str) -> None:
        with self._lock:
            self._counters[name] += 1

    def get(self, name: str) -> int:
        with self._lock:
            return self._counters[name]


# The Pythonic singleton: a module is executed once per process (imports are cached
# in sys.modules), so every `from metrics import registry` gets the same object.
registry = MetricsRegistry()


if __name__ == "__main__":
    with ThreadPoolExecutor(max_workers=8) as pool:
        for _ in range(1000):
            pool.submit(registry.inc, "hits")
    print(registry.get("hits"))  # 1000

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Singleton a wstrzykiwanie zależności
  • Krok po kroku: od Singletona do kontenera
  • Kiedy stosować, a kiedy nie
  • Powiązania z innymi wzorcami
  • W praktyce
  • Szybki test
  • Podsumowanie

Załóż darmowe konto · Zaloguj się