Today I Learned - Rocky Kev

TIL Singleton pattern

POSTED ON:

TAGS:

The Singleton Pattern:

Singleton is a creational design pattern that restricts class to have only one instance, while also creating a global access point to this instance. It is used when control access to a shared resource is needed.

Use this pattern when you need to ensure control access to a resource that might return inconsistencies if it is changed by two different objects at the same time. (Ex. Databases, state of an object)

class Singleton {
    private static instance: Singleton;

    private constructor() { }

    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }

        return Singleton.instance;
    }
}

Via Design Patterns for Web Development


Related TILs

Tagged:

TIL a bunch of new functional programming words

It's so funny seeing developers re-invent functional programming paradigms. We really need to teach this stuff better.

TIL Cleaner data structures

Avoid unnecessary contexts, optional chaining, better error handling, avoid using flags

TIL Cleaner Functions

tl;dr - Limit the number of arguments, Avoid executing multiple actions in a function, Avoid mutation, Avoiding non-negatives, Return Early