{"id":"6b08bd3d80884893657cca05","slug":"singleton","title":"Singleton – jedna instancja i powody, by oddać ją kontenerowi DI","summary":"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.","servedLang":"pl","availableLangs":["pl","en"],"topics":["singleton","abstract-factory","facade","solid"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","creational","singleton","dependency-injection","thread-safety"],"level":"beginner","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":9,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:05.420Z","updatedAt":"2026-11-27T10:10:40.583Z","requestedLang":"pl","theme":{"hero":"minimal","heroMedia":null,"accent":"green","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"Wzorzec Singleton – problem wielu instancji, implementacje bezpieczne wątkowo (Lazy<T>, enum, sync.OnceValue, moduł Pythona), wady globalnego stanu, Singleton a wstrzykiwanie zależności, przykłady z .NET, Javy, Go i Pythona.","wordCount":1665,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Singleton","marks":[{"type":"bold"}]},{"type":"text","text":" to najbardziej znany i zarazem najczęściej krytykowany wzorzec z katalogu GoF. Obiecuje dwie rzeczy: klasa ma "},{"type":"text","text":"dokładnie jedną instancję","marks":[{"type":"bold"}]},{"type":"text","text":" i istnieje "},{"type":"text","text":"globalny punkt dostępu","marks":[{"type":"bold"}]},{"type":"text","text":" do niej. Pierwsza bywa naprawdę potrzebna. Druga – o wiele rzadziej, niż się wydaje."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Prywatny konstruktor plus statyczny punkt dostępu gwarantują jedną instancję na proces."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Implementacja musi być bezpieczna wątkowo – każdy język ma na to gotowy, sprawdzony mechanizm."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Globalny dostęp utrudnia testy i ukrywa zależności; zwykle lepszy jest czas życia "},{"type":"text","text":"singleton","marks":[{"type":"italic"}]},{"type":"text","text":" w kontenerze DI."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"1","label":"instancja na proces","hint":"nie na serwer ani na klaster"},{"value":"2","label":"obietnice wzorca","hint":"jedna instancja i globalny dostęp"},{"value":"0","label":"ukrytych zależności","hint":"tyle chcemy mieć po przejściu na DI"}]}},{"type":"heading","attrs":{"level":2,"id":"problem-liczniki-ktore-licza-do-polowy"},"content":[{"type":"text","text":"Problem: liczniki, które liczą do połowy"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"orders.ts / payments.ts"},"content":[{"type":"text","text":"// orders.ts\nconst metrics = new MetricsRegistry();\nmetrics.increment(\"orders_placed\");\n\n// payments.ts – another module, another registry\nconst metrics = new MetricsRegistry();\nmetrics.increment(\"orders_placed\"); // counted in a different map"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"heading","attrs":{"level":2,"id":"rozwiazanie-prywatny-konstruktor-i-jeden-punkt-dostepu"},"content":[{"type":"text","text":"Rozwiązanie: prywatny konstruktor i jeden punkt dostępu"}]},{"type":"paragraph","content":[{"type":"text","text":"Klasyczny Singleton zamyka konstruktor (nikt z zewnątrz nie zrobi "},{"type":"text","text":"new","marks":[{"type":"code"}]},{"type":"text","text":") i udostępnia statyczną właściwość albo metodę, która przy pierwszym wywołaniu tworzy instancję, a przy kolejnych zwraca tę samą."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  class MetricsRegistry {\n    -instance$ MetricsRegistry\n    -counters Map\n    -MetricsRegistry()\n    +getInstance()$ MetricsRegistry\n    +increment(name)\n    +get(name) long\n  }\n  MetricsRegistry --> MetricsRegistry : instance\n  OrdersModule ..> MetricsRegistry : getInstance()\n  PaymentsModule ..> MetricsRegistry : getInstance()","caption":"Struktura klasycznego Singletona"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Element"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Po co"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"prywatny konstruktor"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"blokuje tworzenie kolejnych instancji przez "},{"type":"text","text":"new","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"statyczne pole z instancją"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"przechowuje jedyny egzemplarz"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"statyczny punkt dostępu"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zwraca instancję, tworząc ją leniwie przy pierwszym użyciu"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"bezpieczeństwo wątkowe"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dwa wątki naraz nie mogą utworzyć dwóch instancji"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"implementacja-w-pieciu-jezykach"},"content":[{"type":"text","text":"Implementacja w pięciu językach"}]},{"type":"paragraph","content":[{"type":"text","text":"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ć "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":". Każdy z języków ma na to gotowe narzędzie: "},{"type":"text","text":"Lazy<T>","marks":[{"type":"code"}]},{"type":"text","text":" w .NET, typ "},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":" w Javie, "},{"type":"text","text":"sync.OnceValue","marks":[{"type":"code"}]},{"type":"text","text":" w Go, a w Pythonie i TypeScripcie – sam system modułów."}]},{"type":"codeGroup","attrs":{"title":"MetricsRegistry"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"MetricsRegistry.cs"},"content":[{"type":"text","text":"using System.Collections.Concurrent;\n\nParallel.For(0, 1000, _ => MetricsRegistry.Instance.Increment(\"hits\"));\nConsole.WriteLine(MetricsRegistry.Instance.Get(\"hits\")); // 1000\n\npublic sealed class MetricsRegistry\n{\n    // Lazy<T> is thread-safe by default (LazyThreadSafetyMode.ExecutionAndPublication).\n    private static readonly Lazy<MetricsRegistry> LazyInstance = new(() => new MetricsRegistry());\n\n    private readonly ConcurrentDictionary<string, long> _counters = new();\n\n    private MetricsRegistry() => Console.WriteLine(\"Registry created once\");\n\n    public static MetricsRegistry Instance => LazyInstance.Value;\n\n    public void Increment(string name) => _counters.AddOrUpdate(name, 1, (_, value) => value + 1);\n\n    public long Get(string name) => _counters.GetValueOrDefault(name);\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"metrics-registry.ts"},"content":[{"type":"text","text":"class MetricsRegistry {\n  private static instance?: MetricsRegistry;\n  private readonly counters = new Map<string, number>();\n\n  private constructor() {\n    console.log(\"Registry created once\");\n  }\n\n  static getInstance(): MetricsRegistry {\n    // JavaScript runs your code on a single thread, so no locking is needed.\n    return (MetricsRegistry.instance ??= new MetricsRegistry());\n  }\n\n  increment(name: string): void {\n    this.counters.set(name, (this.counters.get(name) ?? 0) + 1);\n  }\n\n  get(name: string): number {\n    return this.counters.get(name) ?? 0;\n  }\n}\n\n// Idiomatic alternative: a module is evaluated once, so its exports are shared.\nexport const metrics = MetricsRegistry.getInstance();\n\nmetrics.increment(\"hits\");\nMetricsRegistry.getInstance().increment(\"hits\");\nconsole.log(metrics.get(\"hits\")); // 2"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Metrics.java"},"content":[{"type":"text","text":"import java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.LongAdder;\nimport java.util.stream.IntStream;\n\n// An enum is the singleton recommended in Effective Java:\n// thread-safe, and immune to serialization and reflection attacks.\nenum MetricsRegistry {\n    INSTANCE;\n\n    private final ConcurrentHashMap<String, LongAdder> counters = new ConcurrentHashMap<>();\n\n    public void increment(String name) {\n        counters.computeIfAbsent(name, k -> new LongAdder()).increment();\n    }\n\n    public long get(String name) {\n        LongAdder adder = counters.get(name);\n        return adder == null ? 0 : adder.sum();\n    }\n}\n\npublic class Metrics {\n    public static void main(String[] args) {\n        IntStream.range(0, 1_000).parallel().forEach(i -> MetricsRegistry.INSTANCE.increment(\"hits\"));\n        System.out.println(MetricsRegistry.INSTANCE.get(\"hits\")); // 1000\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"metrics.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype MetricsRegistry struct {\n\tmu       sync.Mutex\n\tcounters map[string]int64\n}\n\n// Default returns the process-wide registry. sync.OnceValue (Go 1.21+) runs the\n// constructor exactly once, even when many goroutines call it at the same time.\nvar Default = sync.OnceValue(func() *MetricsRegistry {\n\tfmt.Println(\"registry created once\")\n\treturn &MetricsRegistry{counters: make(map[string]int64)}\n})\n\nfunc (r *MetricsRegistry) Inc(name string) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.counters[name]++\n}\n\nfunc (r *MetricsRegistry) Get(name string) int64 {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\treturn r.counters[name]\n}\n\nfunc main() {\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 1000; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tDefault().Inc(\"hits\")\n\t\t}()\n\t}\n\twg.Wait()\n\tfmt.Println(Default().Get(\"hits\")) // 1000\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"metrics.py"},"content":[{"type":"text","text":"import threading\nfrom collections import Counter\nfrom concurrent.futures import ThreadPoolExecutor\n\n\nclass MetricsRegistry:\n    def __init__(self) -> None:\n        print(\"registry created once\")\n        self._lock = threading.Lock()\n        self._counters: Counter[str] = Counter()\n\n    def inc(self, name: str) -> None:\n        with self._lock:\n            self._counters[name] += 1\n\n    def get(self, name: str) -> int:\n        with self._lock:\n            return self._counters[name]\n\n\n# The Pythonic singleton: a module is executed once per process (imports are cached\n# in sys.modules), so every `from metrics import registry` gets the same object.\nregistry = MetricsRegistry()\n\n\nif __name__ == \"__main__\":\n    with ThreadPoolExecutor(max_workers=8) as pool:\n        for _ in range(1000):\n            pool.submit(registry.inc, \"hits\")\n    print(registry.get(\"hits\"))  # 1000"}]}]}]},"toc":[{"id":"problem-liczniki-ktore-licza-do-polowy","text":"Problem: liczniki, które liczą do połowy","level":2,"locked":false},{"id":"rozwiazanie-prywatny-konstruktor-i-jeden-punkt-dostepu","text":"Rozwiązanie: prywatny konstruktor i jeden punkt dostępu","level":2,"locked":false},{"id":"implementacja-w-pieciu-jezykach","text":"Implementacja w pięciu językach","level":2,"locked":false},{"id":"singleton-a-wstrzykiwanie-zaleznosci","text":"Singleton a wstrzykiwanie zależności","level":2,"locked":true},{"id":"krok-po-kroku-od-singletona-do-kontenera","text":"Krok po kroku: od Singletona do kontenera","level":2,"locked":true},{"id":"kiedy-stosowac-a-kiedy-nie","text":"Kiedy stosować, a kiedy nie","level":2,"locked":true},{"id":"powiazania-z-innymi-wzorcami","text":"Powiązania z innymi wzorcami","level":2,"locked":true},{"id":"w-praktyce","text":"W praktyce","level":2,"locked":true},{"id":"szybki-test","text":"Szybki test","level":2,"locked":true},{"id":"podsumowanie","text":"Podsumowanie","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":39,"visibleBlocks":14,"resources":[{"id":"6b0857a53c96f2d34d0b321f","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=hUE_j6q0LTQ","embedUrl":"https://www.youtube-nocookie.com/embed/hUE_j6q0LTQ","title":"Singleton Pattern – Design Patterns (ep 6)","description":"","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/hUE_j6q0LTQ/hqdefault.jpg","durationSec":null,"lang":"en","topics":["singleton"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:37.809Z","updatedAt":"2026-11-26T16:00:37.809Z"},{"id":"6b0857bf3c96f2d34d0b4289","type":"article","provider":"web","url":"https://gameprogrammingpatterns.com/singleton.html","embedUrl":null,"title":"Singleton · Design Patterns Revisited · Game Programming Patterns","description":"","author":"Robert Nystrom","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["singleton"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:26:37.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T23:13:50.401Z"},{"id":"6b0857c23c96f2d34d0b457a","type":"article","provider":"web","url":"https://milanjovanovic.tech/blog/using-scoped-services-from-singletons-in-aspnetcore","embedUrl":null,"title":"Using Scoped Services From Singletons in ASP.NET Core","description":"Did you ever need to inject a scoped service into a singleton service? I'll explain how you can solve this problem and safely use scoped services from within…","author":"Milan Jovanović","thumbnailUrl":"https://milanjovanovic.tech/blog-covers/mnw_077.png","durationSec":null,"lang":"en","topics":["singleton"],"techs":["dotnet"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2024-02-17T00:00:00.000Z","popularity":50,"verifiedAt":"2026-11-26T11:29:11.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c33c96f2d34d0b4665","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6223299W","embedUrl":null,"title":"Effective Java","description":"","author":"Joshua Bloch","thumbnailUrl":"https://covers.openlibrary.org/b/id/1176573-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["java"],"tags":["book"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2001-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857be3c96f2d34d0b4210","type":"article","provider":"web","url":"https://martinfowler.com/articles/injection.html","embedUrl":null,"title":"Inversion of Control Containers and the Dependency Injection pattern","description":"Explaining the Dependency Injection pattern, by contrasting it with Service Locator. The choice between them is less important than the principle of separating configuration from use.","author":"Martin Fowler","thumbnailUrl":"https://martinfowler.com/logo-sq.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["martin-fowler"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":75,"verifiedAt":"2026-11-26T11:07:14.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Wzorce projektowe – podstawy","summary":"Sześć pytań o klasyczne wzorce GoF: grupy, przeznaczenie i różnice.","servedLang":"pl","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-creational","title":"Wzorce kreacyjne GoF","items":[{"slug":"factory-method","title":"Metoda wytwórcza (Factory Method) – niech podklasa zdecyduje, co powstaje","current":false},{"slug":"abstract-factory","title":"Fabryka abstrakcyjna (Abstract Factory) – całe rodziny obiektów, które do siebie pasują","current":false},{"slug":"builder","title":"Budowniczy (Builder) – złożone obiekty krok po kroku","current":false},{"slug":"prototype","title":"Prototyp (Prototype) – nowy obiekt jako kopia gotowego wzorca","current":false},{"slug":"singleton","title":"Singleton – jedna instancja i powody, by oddać ją kontenerowi DI","current":true}]}],"prev":{"slug":"prototype","title":"Prototyp (Prototype) – nowy obiekt jako kopia gotowego wzorca"},"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}