📖
Docs
  • Hi there 👋
  • Python
    • Tutorial
      • Class
      • Context Managers
      • Iterators and Iterables and generators
      • Lambda Operator
      • Decorators
      • Lập trình Ä‘a luồng
      • Singleton
      • Logging
      • Best practices
    • Django
      • Lazy queryset
      • Sql injection
      • Transaction
    • Flask
    • Fastapi
  • Struct data and algorithms
    • Struct data
    • Algorithms
  • database
    • Nosql và RDBMS
    • Index sql
    • Inverted Index
    • Migrate database best
    • Datatype
  • Cache
    • Caching strategies
    • Cache replacement policies
  • Message queue
    • Message queue
  • Other
    • Clean code
    • Design pattern
    • Encode-decode
    • Security
    • Docker
    • Celery
  • deploy
    • Jenkins
Powered by GitBook
On this page
  • Cách 1
  • Cách 2
  1. Python
  2. Tutorial

Singleton

Cách 1

class Singleton(object):
    _instance = {}

    def __new__(cls, *args, **kwargs):
        if not isinstance(cls._instance, cls):
            cls._instance = super().__new__(cls)
        return cls._instance


class MyClass(Singleton):
    pass

Cách 2

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class MyClass(metaclass=Singleton):
    pass
PreviousLập trình đa luồngNextLogging

Last updated 2 years ago