Singleton Pattern - Design Patterns in JavaScript

preview_player
Показать описание

The singleton pattern limits the instantiation of an object to a single instance, helps coordinate data, and functions across the application, and can help to reduce unnecessary memory usage.

0:00 Intro
1:46 Simple example
5:52 Realistic example with a classe
8:56 Realistic example with a function
11:50 Outro

Why not use singletons?
* May introduce unnecessary restrictions
* Singletons are available anywhere in the application by anything, which may mean that dependencies may not be immediately visible, meaning developers may need to know the inner workings of the singleton
* It May be difficult to test

Requirements
* Ensure that only one instance of the singleton exists
* Provide global access to the instance

Examples
* Logging function - Don't want a new instance of the logger for every log
* Global config - Config should come from a single source of truth
* Database connections - Many instances can increase memory usage

Video structure
* Simple example
* Database connection example with a class
* Database connection example with a function

🌎 Follow me here:
Рекомендации по теме
Комментарии
Автор

Great videos, easy to understand. Keep posting, thanks.

sumansen
Автор

Wonderful, I love the explanation, Thanks

Gurralanarayanareddy
Автор

try this next time
class CounterService {
static instance = null;
constructor() {
if (CounterService.instance && CounterService.instance instanceof CounterService) {
return this.instance;
}
this.counter = counter;
counter++;
}

static getInstance() {
if (!this.instance) {
this.instance = new CounterService();
}
return this.instance;
}
}

amitshimon