Sobes.tech
Junior — Middle

Can you explain the principle of the Singleton pattern and its features?

sobes.tech AI

Answer from AI

The singleton pattern guarantees that a class has only one instance and provides a global point of access to it. This is useful for managing resources or state centrally.

Features:

  • Usually, the constructor is made private or protected to prevent creating new instances from outside.
  • The instance is created lazily (upon first access) or immediately at class load.
  • In multithreaded environments, thread safety must be ensured during instance creation.

Example in Python using a decorator:

def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance

@singleton
class Logger:
    def log(self, msg):
        print(msg)

logger1 = Logger()
logger2 = Logger()
print(logger1 is logger2)  # True

Here, the Logger class will have only one instance.

Can you explain the principle of the Singleton… - sobes.tech