Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions src/Singleton/Conceptual/NonThreadSafe/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,16 @@
EN: Singleton Design Pattern

Intent: Lets you ensure that a class has only one instance, while providing a
global access point to this instance.
global access point to this instance. One instance per each subclass (if any).

RU: Паттерн Одиночка

Назначение: Гарантирует, что у класса есть только один экземпляр, и
предоставляет к нему глобальную точку доступа.
предоставляет к нему глобальную точку доступа. У каждого наследника класса тоже
будет по одному экземпляру.
"""


from __future__ import annotations
from typing import Optional


class SingletonMeta(type):
"""
EN: The Singleton class can be implemented in different ways in Python. Some
Expand All @@ -26,12 +23,20 @@ class SingletonMeta(type):
метаклассом, поскольку он лучше всего подходит для этой цели.
"""

_instance: Optional[Singleton] = None
_instances = {}

def __call__(self) -> Singleton:
if self._instance is None:
self._instance = super().__call__()
return self._instance
def __call__(cls, *args, **kwargs):
"""
EN: Possible changes to the value of the `__init__` argument do not
affect the returned instance.

RU: Данная реализация не учитывает возможное изменение передаваемых
аргументов в `__init__`.
"""
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]


class Singleton(metaclass=SingletonMeta):
Expand Down
27 changes: 17 additions & 10 deletions src/Singleton/Conceptual/ThreadSafe/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@
EN: Singleton Design Pattern

Intent: Lets you ensure that a class has only one instance, while providing a
global access point to this instance.
global access point to this instance. One instance per each subclass (if any).

RU: Паттерн Одиночка

Назначение: Гарантирует, что у класса есть только один экземпляр, и
предоставляет к нему глобальную точку доступа.
предоставляет к нему глобальную точку доступа. У каждого наследника класса тоже
будет по одному экземпляру.
"""


from __future__ import annotations
from threading import Lock, Thread
from typing import Optional


class SingletonMeta(type):
Expand All @@ -23,7 +21,7 @@ class SingletonMeta(type):
RU: Это потокобезопасная реализация класса Singleton.
"""

_instance: Optional[Singleton] = None
_instances = {}

_lock: Lock = Lock()
"""
Expand All @@ -35,6 +33,13 @@ class SingletonMeta(type):
"""

def __call__(cls, *args, **kwargs):
"""
EN: Possible changes to the value of the `__init__` argument do not
affect the returned instance.

RU: Данная реализация не учитывает возможное изменение передаваемых
аргументов в `__init__`.
"""
# EN: Now, imagine that the program has just been launched.
# Since there's no Singleton instance yet, multiple threads can
# simultaneously pass the previous conditional and reach this
Expand Down Expand Up @@ -63,9 +68,10 @@ def __call__(cls, *args, **kwargs):
# экземпляр одиночки уже будет создан и поток не сможет
# пройти через это условие, а значит новый объект не будет
# создан.
if not cls._instance:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]


class Singleton(metaclass=SingletonMeta):
Expand Down Expand Up @@ -101,7 +107,8 @@ def test_singleton(value: str) -> None:
# RU: Клиентский код.

print("If you see the same value, then singleton was reused (yay!)\n"
"If you see different values, then 2 singletons were created (booo!!)\n\n"
"If you see different values, "
"then 2 singletons were created (booo!!)\n\n"
"RESULT:\n")

process1 = Thread(target=test_singleton, args=("FOO",))
Expand Down