10.1. Singleton

10.1.1. Rationale

  • EN: Singleton

  • PL: Singleton

  • Type: object

10.1.2. Use Cases

  • Database connection pool

  • HTTP Gateway

10.1.3. Design

10.1.4. Implementation

class Singleton:
    __instance = None

    @classmethod
    def get_instance(cls):
        if not cls.__instance:
            cls.__instance = ...
        return cls.__instance


# Creating first instance for the first time
first = Singleton.get_instance()

# Connecting for the second time
# Will use existing instance
second = Singleton.get_instance()
class DB:
    __connection = None

    @classmethod
    def connect(cls):
        if not cls.__connection:
            print('Establishing connection...')
            cls.__connection = ...
        return cls.__connection


# Connecting for the first time
# Will establish new connection
first = DB.connect()

# Connecting for the second time
# Will use existing connection to the DB
# The same handle as `first`
second = DB.connect()

10.1.5. Assignments

Todo

Create assignments