Singleton Pattern - Design Patterns

Web Dev Simplified · Intermediate ·🏗️ Systems Design & Architecture ·7y ago

Key Takeaways

The video covers the Singleton design pattern, its implementation, and use cases, as well as its potential drawbacks, such as global variables, testing, and coupling issues, and demonstrates how to refactor code to use the Singleton pattern and implement it in a Logger class.

Full Transcript

in today's video we're going to be going over one of the most controversial yet easiest to understand design patterns the singleton design pattern we're going to cover what it is when you should use it when you shouldn't use it and we're going to go over some code that is not using the singleton design pattern and then we're going to refactor to use the singleton design pattern like it should be before we start refactoring any code to use the singleton pattern let's first talk about what it is in essence the singleton pattern is just a way of creating a single object that is shared amongst a bunch of different resources throughout your application without having to recreate that object or losing the information inside of it all of the state for that object the variables methods all of those are shared among all these different other objects that are using it and there's just one source of information for this object and there's only ever a single type of this object created this is why it is called a singleton because your application will only and can only have one type of this object instantiate it at a time and all places that use this object share that one single instance of the object so as you can see from this example here we have our singleton in the middle which is our one single object and all of our other objects a b c and d are all using that one instance of that shared object that is going to have all the state for that singleton inside of it and they don't create their own instance of that object each time and that's really all the singleton pattern is is a way to create a single object that have shared amongst a bus your different parts of your application but this can lead to some problems with creating global variables since they Singleton's are essentially global to your entire application having a single object that is global to your application and controls so much of your application can be incredibly hard to test such you need to have that single object in order to test anything and it can create a bunch of coupling between the different parts your application where all of your application relies on this singleton object so it becomes very hard to change or refactor that object since all the rest of your application is so dependent on it lastly you can run into what's called a race condition we're changing things inside of this singleton in different parts of your application at the same time can cause data to get overwritten or not read correctly because they're all trying to access the exact same information at the same exact time because of these downsides some people said that you should know ever use the singleton design pattern in any of your applications but I believe that there are certain niche uses for the singleton design pattern where it can become better than using a non singleton design pattern in those cases where you have certain sets of small information that needs to be shared throughout all of your application using a singleton pattern in order to get all of that information into one coherent place can be easier to work with than having to create a bunch of different classes and making sure that those classes save the information properly and so on so let's dive into an example of some code that does not use the singleton pattern which I believe should use a singleton pattern and then let's actually implement the singleton design pattern in that code here I have Visual Studio code open on the left with all the code for this project and on the right I just have the console so we can view the output of our code before we get started any further I do want to say if you are not familiar with the module system for exporting and importing modules in JavaScript make sure to check out my export import module of video which will be linked in the cards in the description below because we're going to be using that heavily in this example to start with we have this fancy logger class which all it does is you create a new one and it creates an empty array of vlogs which are all the things that you log inside of it it has a function for logging out any message it'll add that log to this log array that we created and it'll also log it to the console so that we can see it and then lastly we have a method just to print out the number of vlogs that we have saved inside of our class so far and then we're exporting them so we can use this fancy logger module and you are in our application and we have two uses where we want to use it we have this first use j/s class which we are going to use inside of this implementation class which we are going to implement here soon we have a second use which is exactly the same as the first one but it's just a second use case and then finally we have our index.js file which is what's actually being run over here inside of our browser for our console logs and all this does is take our first and second implementation and it's going to call both of those methods that we implement so let's start by implementing this first use as you can see we've already imported our logger and created a new instances it so what side of here let's log the number of logs that we have so we could just say print log count and we should know that this should be 0 and then we just want to log something to our logger so let's just say my log first file so that we know it were in the first file and then as soon as we're done that we're going to print out the log count again and we're just going to copy that because we're gonna do the exact same thing and our second use case file here but it said we're going to print second file instead of first file and as you can see our first file has already run and you see it says zero logs printed out first file and now one Long's so now if we save this file we'll see that both of our functions will run but you'll see that it runs zero logs first file and we have one log in the logger and then it goes back to having zero logs inside of our logger and then prints out the second file and says that we have one log and that's because in each of these files we're creating a new instance of this fancy logger so we don't have all of that shared information from the previous instance of the blogger because we're creating a new one every time that we import it and use it this is a great use case for where we're going to want to use the singleton pattern since we want all uses of our fancy logger class to actually have the number of vlogs in it that we've logged so far so let's go back to our fancy logger here and implement this as if it was a singleton the first thing we want to do is we don't actually want to export the class itself because we never want to actually use the class we just want to use a single instance of this class so it has the entire idea of the singleton pattern and since we only want a single instance of this class we want to make sure that we only ever create one single instance in our constructor so in order to do that we can just use a static variable on our fancy logger so we can say fancy logger instance which in this case is just a variable that we're creating and we want this to always be a single instance of the fancy logger and no other instance could overwrite this so if this instance is null that means that we have not actually created a fancy logger yet so we want to create a new one so we're going to X tan XI ate this dot logs to be an empty array and then we're going to take that instance variable we're just going to set that to this which is the new fancy logger instance we created so now every single time that we run this constructor here if there's no instance created yet so if it's the very first time we're going to initialize it and set our instance to whatever work rating then the second time that we run this it's just going to return down here we're just going to say return fancy lager instance and essentially what this is saying is that we always want to return that single instance every single time from our constructor instead of returning a bunch of different instances every time and then down here what we want to do is we want to create that fancy lager instance before we export it so we can just create a variable we'll just call it new fancy longer and now we have an actual instance of our singleton but to be able to make sure that nobody can actually mess with this we're going to use a method called object freeze which will pretty much prevent this object from being changed in any way we'll just pass in our lager here so now this lager class cannot have any new methods or variables added on to it or removed from it by our code and then lastly we just want to export in the default that lager so now we're actually exporting an instance of our lager instead of a class so instead of all of our use cases here we know that we're actually importing a instance instead of the class so we can completely remove this line we're creating the new version of the class and we can do the same thing in here remove this line and now if you save that you see that we get zero logs the first time that we use it it prints out first file and then it has one log and when we get into that second use case in this file here even though we're importing the logger this import is just importing the exact same instance so we still have that one log being persisted we print out our log and now we have two logs inside of our fancy logger and that's because we're using one single instance as I mentioned before and that's all there is to using the singleton design pattern if you guys did enjoy this video make sure to check out my other design pattern videos and JavaScript videos which are going to be linked over here and subscribe to the channel if you enjoyed the content for more content just like this in the future thank you guys very much for watching and have a good day

Original Description

The singleton pattern is one of the most controversial yet easiest to implement design patterns. Many people say you should never use the singleton design pattern, but there are still plenty of cases where the singleton pattern is the perfect solution. In this video I will explain what the singleton pattern is, when you should and should not use it, and go over an example of refactoring some code to use the singleton pattern. Design Pattern Playlist: http://bit.ly/2QrGnDq Design Pattern Repository: https://github.com/WebDevSimplified/Design-Patterns Twitter: https://twitter.com/DevSimplified GitHub: https://github.com/WebDevSimplified CodePen: https://codepen.io/WebDevSimplified #SingletonPattern #DesignPatterns #Programming
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Web Dev Simplified · Web Dev Simplified · 55 of 60

1 Introduction to Web Development || Setup || Part 1
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
2 Introduction to Web Development || Understanding the Web || Part 2
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
3 Introduction to HTML || Your First Web Page || Part 1
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
4 Introduction to HTML || Basic HTML Elements || Part 2
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
5 Introduction to HTML || Advanced HTML Elements || Part 3
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
6 Introduction to HTML || Links and Inputs || Part 4
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
7 Learn Git in 20 Minutes
Learn Git in 20 Minutes
Web Dev Simplified
8 5 Must Know Sites For Web Developers
5 Must Know Sites For Web Developers
Web Dev Simplified
9 10 Best Visual Studio Code Extensions
10 Best Visual Studio Code Extensions
Web Dev Simplified
10 Learn CSS in 20 Minutes
Learn CSS in 20 Minutes
Web Dev Simplified
11 How to Style a Modern Website (Part One)
How to Style a Modern Website (Part One)
Web Dev Simplified
12 How to Style a Modern Website (Part Two)
How to Style a Modern Website (Part Two)
Web Dev Simplified
13 3D Flip Button Tutorial
3D Flip Button Tutorial
Web Dev Simplified
14 How to Style a Modern Website (Part Three)
How to Style a Modern Website (Part Three)
Web Dev Simplified
15 Animated Loading Spinner Tutorial
Animated Loading Spinner Tutorial
Web Dev Simplified
16 How to Write the Perfect Developer Resume
How to Write the Perfect Developer Resume
Web Dev Simplified
17 Animated Text Reveal Tutorial
Animated Text Reveal Tutorial
Web Dev Simplified
18 Learn Flexbox in 15 Minutes
Learn Flexbox in 15 Minutes
Web Dev Simplified
19 Custom Checkbox Tutorial
Custom Checkbox Tutorial
Web Dev Simplified
20 Start Contributing to Open Source (Hacktoberfest)
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
21 JavaScript Shopping Cart Tutorial for Beginners
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
22 Responsive Video Background Tutorial
Responsive Video Background Tutorial
Web Dev Simplified
23 1,000 Subscriber Giveaway
1,000 Subscriber Giveaway
Web Dev Simplified
24 How To Prevent The Most Common Cross Site Scripting Attack
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
25 Transparent Login Form Tutorial
Transparent Login Form Tutorial
Web Dev Simplified
26 The Forgotten CSS Position
The Forgotten CSS Position
Web Dev Simplified
27 How to Code a Card Matching Game
How to Code a Card Matching Game
Web Dev Simplified
28 10 Must Install Visual Studio Code Extensions
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
29 Learn CSS Grid in 20 Minutes
Learn CSS Grid in 20 Minutes
Web Dev Simplified
30 Learn JSON in 10 Minutes
Learn JSON in 10 Minutes
Web Dev Simplified
31 10 Essential Keyboard Shortcuts For Programmers
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
32 What Is The Fastest Way To Load JavaScript
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
33 Differences Between Var, Let, and Const
Differences Between Var, Let, and Const
Web Dev Simplified
34 How To Install MySQL (Server and Workbench)
How To Install MySQL (Server and Workbench)
Web Dev Simplified
35 Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
Web Dev Simplified
36 How To Solve SQL Problems
How To Solve SQL Problems
Web Dev Simplified
37 What Are Design Patterns?
What Are Design Patterns?
Web Dev Simplified
38 Null Object Pattern - Design Patterns
Null Object Pattern - Design Patterns
Web Dev Simplified
39 Your First Node.js Web Server
Your First Node.js Web Server
Web Dev Simplified
40 How To Setup Payments With Node.js And Stripe
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
41 How To Learn Any New Programming Skill Fast
How To Learn Any New Programming Skill Fast
Web Dev Simplified
42 Asynchronous Vs Synchronous Programming
Asynchronous Vs Synchronous Programming
Web Dev Simplified
43 JavaScript ES6 Arrow Functions Tutorial
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
44 Are You Too Old To Learn Programming?
Are You Too Old To Learn Programming?
Web Dev Simplified
45 JavaScript Cookies vs Local Storage vs Session Storage
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
46 JavaScript Promises In 10 Minutes
JavaScript Promises In 10 Minutes
Web Dev Simplified
47 Builder Pattern - Design Patterns
Builder Pattern - Design Patterns
Web Dev Simplified
48 JavaScript == VS ===
JavaScript == VS ===
Web Dev Simplified
49 JavaScript ES6 Modules
JavaScript ES6 Modules
Web Dev Simplified
50 8 Must Know JavaScript Array Methods
8 Must Know JavaScript Array Methods
Web Dev Simplified
51 CSS Variables Tutorial
CSS Variables Tutorial
Web Dev Simplified
52 JavaScript Async Await
JavaScript Async Await
Web Dev Simplified
53 How To Choose Your First Programming Language
How To Choose Your First Programming Language
Web Dev Simplified
54 Easiest Way To Work With Web Fonts
Easiest Way To Work With Web Fonts
Web Dev Simplified
Singleton Pattern - Design Patterns
Singleton Pattern - Design Patterns
Web Dev Simplified
56 Responsive Navbar Tutorial
Responsive Navbar Tutorial
Web Dev Simplified
57 CSS Progress Bar Tutorial
CSS Progress Bar Tutorial
Web Dev Simplified
58 Learn GraphQL In 40 Minutes
Learn GraphQL In 40 Minutes
Web Dev Simplified
59 What is an API?
What is an API?
Web Dev Simplified
60 Learn How To Build A Website In 1 Hour!
Learn How To Build A Website In 1 Hour!
Web Dev Simplified

The Singleton design pattern is a way to create a single object shared amongst different resources throughout an application, but it can lead to problems with global variables, testing, and coupling. This video demonstrates how to implement the Singleton pattern in a Logger class and how to refactor code to use it.

Key Takeaways
  1. Refactor code to use the Singleton design pattern
  2. Implement the Singleton design pattern in the code
  3. Create a new instance of the Logger class
  4. Log a message to the Logger class
  5. Print the number of vlogs saved
  6. Use a static variable to store the single instance of the Logger class
  7. Create a new instance of the Singleton class
  8. Use Object.freeze() to prevent modification of the Singleton instance
  9. Export an instance of the Singleton class instead of the class itself
💡 The Singleton pattern can be useful in certain situations, but it can also lead to problems with global variables, testing, and coupling, so it should be used judiciously.

Related AI Lessons

What OOP Actually Buys You (And Why “Real World Modeling” Is a Lie)
Learn the actual benefits of Object-Oriented Programming (OOP) and why 'real world modeling' is a misconception
Medium · Programming
Data Partitioning in System Design: Why Every Scalable Application Depends on It
Learn how data partitioning enables scalable applications to handle growth without failing
Medium · Programming
Why Realtime Collaboration Is Harder Than It Looks?
Realtime collaboration is a complex distributed systems problem that requires careful engineering, not just a simple UI feature
Medium · JavaScript
Podcast: Architectural Patterns: Moving Beyond Cloud-Native to Local-First - Insights from Adam Wiggins
Learn how to design local-first architectures that combine cloud-based collaboration with local software performance and data ownership
InfoQ AI/ML
Up next
Retracing It All With My Son
Ginny Clarke
Watch →