Published on

Design Patterns: Singleton

Authors
  • avatar
    Name
    Loi Tran
    Twitter

Introduction

Purpose: Ensures that a class has only one instance and provides a global point of access to it.

Use Cases: Database connections, logging, cache management, global state & more.

class Singleton:
    _instance = None

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

# Usage
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)  # True
class Singleton {
    constructor() {
        if (Singleton.instance) {
        return Singleton.instance
        }
        Singleton.instance = this
    }
}

const obj1 = new Singleton()
const obj2 = new Singleton()
console.log(obj1 === obj2)
class Singleton {
    static final Singleton _instance = Singleton._internal();

    Singleton._internal();

    factory Singleton() {
        return _instance;
    }
}

// Usage
void main() {
    var obj1 = Singleton();
    var obj2 = Singleton();
    print(obj1 == obj2);  // true
}
class Logger
    @instance = new

    private_class_method :new

    def self.instance
        @instance
    end
end

log1 = Logger.instance
log2 = Logger.instance
puts log1 == log2  # true