Skip to content

Commit

Permalink
Add singleton metaclass example
Browse files Browse the repository at this point in the history
  • Loading branch information
vyahello committed Mar 19, 2022
1 parent e5202c6 commit fc116f8
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,20 @@ Useful if you want to share cached information to multiple objects.
from typing import Any, Dict


class SingletonMeta(type):
"""Singleton metaclass implementation."""

def __init__(cls, cls_name: str, bases: tuple, namespace: dict):
cls.__instance = None
super().__init__(cls_name, bases, namespace)

def __call__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super().__call__(*args, **kwargs)
return cls.__instance
return cls.__instance


class Singleton:
"""Makes all instances as the same object."""

Expand Down
24 changes: 24 additions & 0 deletions patterns/creational/singleton.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,31 @@
from typing import Any, Dict


class SingletonMeta(type):
"""Singleton metaclass implementation."""

def __init__(cls, cls_name: str, bases: tuple, namespace: dict):
cls.__instance = None
super().__init__(cls_name, bases, namespace)

def __call__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super().__call__(*args, **kwargs)
return cls.__instance
return cls.__instance


class Single(metaclass=SingletonMeta):
"""Singleton object."""

pass


class Singleton:
"""Makes all instances as the same object."""

_instance: "Singleton"

def __new__(cls) -> "Singleton":
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls)
Expand All @@ -29,6 +51,8 @@ class Bar:
pass


print(Single() is Single())

singleton_one: Singleton = Singleton()
singleton_two: Singleton = Singleton()

Expand Down

0 comments on commit fc116f8

Please sign in to comment.