Singleton Design Pattern in C# - Do it THAT way

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if you want to become an expert c-sharp developer you have to know about software design patterns one very popular pattern is the Singleton pattern so if you need that pattern for your job right now or if you just want to become a better c-sharp developer stick around until the end of the video to really find out how to master this pattern now let's get started [Music] on the c-sharp Singleton design pattern is incredibly popular and if you are interested in in-depth software engineering you have to know how to use it so here I got a brand new console application in dotnet 6 and by default we got that program.cs file you can see it right here with that nice top level statement however I created a new class called upload service so I don't want to call it Singleton or something like that because that's not a typical naming convention so let's just assume that we want to create any kind of functionality and I decided to stick around with an upload service so something that uploads something to the internet or something like that and we want to have that class as a Singleton implemented now let's talk about the words Singleton first so Singleton means that you can only have a single instance of that class to be created right Singleton single makes sense so if we have one instance of the upload service then there can not be another one that's the Singleton design pattern so there's one important information that you should know about the Singleton design pattern and it is that we have to make it thread safe and you will learn what that means and how to do it during the video alrighty so let's get started let's turn this internal class here that I just have created into a Singleton okay so here we got our internal class the first thing that I want to do is I want to remove the internal we will just replace that with another keyword in a second let's get started by creating a Constructor so simply write down ctor and hit tap tap now best practice is not to add any kind of parameters because that's against the pattern if you would need any parameters then a Singleton is not really what you're looking for because it's a parameter for sure can be variable but we only want to have one specific instance there are other design patterns which you should use instead for example the factory one so we want to keep that Constructor here empty now let me shorten that up let me bring that into a single line of code here so that we don't want to add anything and very important we want to switch that not from being public but private instead because only the class itself should be able to create an instance so we should not be able to create instances of that upload service from outside of this class because well that's against the Singleton pattern if any other class from outside here could create an instance then we could not be sure that only a single instance of that service exists now next up we want to add a reference to the actual instance this is why we add a private static very important make it static let's call it upload service right because the instances of this type and let's call it instance now we make it private because in a second we will create a static method which gives us the information about the instance so we can make it private here and we make it static so that we don't need any instantiation well to have a Singleton instance so now let's write down a method which gives us the information about the instance you want to call that method to get the instance actually we want to make it public we want to make it static and for sure it Returns the upload service and then let's call it instance awesome great now the basic code behind this you can see that already suggested here is like if the instance that we have here in line 13 if that instance is null so if it's equals to null so if we don't have an instance we want to create one so new upload service right so if we don't have an instance create an instance and now finally we want to return something from that method and for sure we want to return the instance awesome so basically this would be a very simplified version of a Singleton it would be already working but there is this one problem however as you can see from a logical side of you that will work we don't have an instance we create one but if we have an instance so that one will not become true the if statement will become false right and we will directly return the existing instance so if we don't have an instance we create a new one if we have an instance we simply return the existing one awesome so the next part of this video is really very very important but before we get to that make sure to subscribe to our channel so that you no longer miss any upcoming.net related videos and if this video helps you out and you like it make sure to give it a thumb up to support our Channel and so that we know what content tent you really want to see oh and by the way we got an online course a very unique online course we call it the c-sharp progress Academy well it teaches you asp.net core angular software design patterns and test driven development basically in 21 days you can go through it in your own speed and I'm absolutely sure about that this is the fastest way to become a better cshop developer so if you really want to become a.net hero check out our C sharp progress Academy you can find the link in the description below or in the info card popping up right now great so now let's get to the second part of this video basically even though this pattern here is working right now it's pretty simplified because in real world we need to create a Singleton pattern which is thread safe so as long as you only have a single threat in your application this pattern here is fine but if you have a multi-threaded application we need to make sure that we add a lock here so that another thread is not creating a new instance again when we start the program so basically so that you get the ideas like if we have multiple threads and we started the application and those threads are starting we need to make sure that only one thread is creating the instance and not another thread is also creating one because it sees like okay the instance is not and this is why we use the keyword lock so we create a log object and then one thread will reach this position the lock and all other threads will wait until it's finished but we will see that in action now it sounds more complicated than it is and it's really a nice practice and if you are a well c-shot beginner or kind of intermediate I'm pretty sure that you have never used the lock before now let's see that in action let's create a private static and read-only object and this one we call it lock and it's basically a new object this is all what we have to do right here so just a simple static read-only object now the magic happens inside of our instance creation so right here right at the position where the instance is null right just imagine that we have multiple threads which come into that instance method and they see okay the instance is not so at the moment we start the program and the threads reach that position the threads will see that the instance is now and multiple instances would get created and that's a violation against the Singleton pattern so what we want to do is we want to use the lock keyword here and we want to lock and send in our lock object now inside here we basically want to repeat the code that we have right here so again inside the lock I want to say if instance is equals to null then we want to create a new instance of that upload service so take that line of code here cut it out paste it back in here and we're done so let me explain that to you so we start the program and both threads are starting they will come both into that instance method here they will both see that the instance is null because it doesn't didn't get created yet so in the previous code both threads would now create an instance and that's wrong because where we Singleton pattern so we only have a single instance shared between all threads the entire application only has one instance of it so both threads are inline 18 right now they will come to line 21 and the lock keyword basically means that now a single thread will proceed through it while the other threads are waiting so let's say thread 1 will work through this and thread 2 is waiting in line 20 until the first thread is done so from the side of thread one we will now go inside this code block you will again see instances null he will create an instance now so now we have an instance in our application okay so we are done let's switch over to the second one because he will wait at the log or he's still waiting but now thread one is done so thread 2 will proceed from here he will now take a look again is the instance null but no the instance is not null anymore because thread one created an instance and so the if statement will not become true and instead he will know about the instance of the object which thread 1 has created and he will simply add that if statement and return the existing instance and in that way we have created or implemented a Singleton soft software design pattern which is thread safe alrighty so now let's prove that this is actually working let's switch over to our program.cs and let's first of all start using our upload service here now first things first let's start using the system so that we are able to create threads and that's what we want to do we want to go ahead and we're going to create a thread here so thread let's call it T1 just to keep it short equals to a new thread inside that thread we want to go ahead and create a new let's just do it that way Arrow function here and we basically just want to run a single line of code we want to call our upload service and for that we're gonna use the namespace design pattern Singleton here there we go so that we get access to the service and then we want to just call the upload service here and we got a method inside of it which is called instance for sure so let me just break that into another line of code there we go and let me add a break point here so for instance there we go and I want to add a break point here in line seven and I want to copy that over and I want to go thread to the same stuff again I want to add a breakpoint now let's simply start both threads so start both of them very important that we do it in in that order here so that we're really able to test it in a valid way and then we want to join so T1 T2 stalking them joining them there we go now we want to have any kind of idea or something like that so that we can really make a difference between um between well the instances right so this is why we go into our instance here let's simply add an integer here let's call it ID and right here at the upload service let's set a property let's call it prop let's call it int ID there we go we can simply call get we make private set really this is just for validation so get private set and when we create a new instance we want to take the instance and set the ID to whatever the user submits right here in the instance method so let's switch over to the program let's say this is instance id1 and this is instance id2 right now let's hit start and basically both instances should be id1 right because we create here upload service instance we set in one and we call it a second time instance when we send in the two but that one should not create a new instance so the first one should get used instead so if we hover above instance and we see id1 which is fine perfect right so let's press continue now we come to the second break point let's take a look at instance again and the ID is still one if we take a look we could see okay the instance run into a log so we waited at the lock with the second thread and the first fret created the instance with id1 so our second thread never created a new instance and never set the ID so this is the proof that even though we have two separated threads we have a single instance used in our application now now at the very beginning I removed the internal axis modifier and I said we will replace it and we will replace it with this sealed keyword which basically means that you are not able to inherit from that upload service which makes again sure that we only have a single instance of that class in our application awesome so now you know how to apply the c-sharp Singleton software design pattern and if you like that video make sure to give it a thumb up and to subscribe to our channel so that you no longer miss any advanced cshop.net videos again if you really want to dig deeper into advanced c-sharp topics make sure to check out our C sharp progress Academy you can find the link in the description below thanks again for watching and I see you next time [Music]
Info
Channel: tutorialsEU - C#
Views: 17,191
Rating: undefined out of 5
Keywords: dotnet, csharp, dotnet core, .net core tutorial, .net core, .net, c#, Tutorials, Tutorial, Programming, Course, Learn, Step by step, guide, programmer, core, code, c sharp, sharp, net6, 6.0, .net framework, programming, visual studio, programming for beginners, coding, how to code, dot net, c# programming, tim corey, software development, singleton, gang of four, singleton design pattern, design pattern, design patterns, data structures, java, dynamic programming, singleton in c#, pattern
Id: r6Y0SmbufmU
Channel Id: undefined
Length: 13min 15sec (795 seconds)
Published: Thu Nov 24 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.