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