Back to articles
Design Pattern Anatomy - Singleton Pattern
How-ToTools

Design Pattern Anatomy - Singleton Pattern

via Dev.toDaniel Breen

Introduction The Singleton pattern restricts the instantiation of a class to a single instance and provides a global point of access to it. It is useful when exactly one object is needed to coordinate actions across the system. Example The example below demonstrates a simple implementation of the singleton pattern to create a counter. class Counter { private static instance : Counter ; private _count : number ; private constructor () { this . _count = 0 ; // Initialize the count to 0 to prevent errors when incrementing } public static getInstance (): Counter { if ( ! Counter . instance ) { Counter . instance = new Counter (); } return Counter . instance ; } public increment (): void { this . _count ++ ; } public getCount (): number { return this . _count ; } } Anatomy Breakdown Private Static Variable A private static variable that holds the single instance of the class. private static instance : Counter ; Private Constructor A private constructor to prevent direct instantiation of the

Continue reading on Dev.to

Opens in a new tab

Read Full Article
5 views

Related Articles