I'm sorry for pause in writing new posts about design patterns.
So, today I'm going to write a post about the most popular and well-known design pattern - Singleton.
The essence of Singleton is to provide :
- exactly one instance of class across the system;
- simple access to it.
The implementation of Singleton based on creation a class with a method(or property in .NET) that creates an instance of this class if one doesn't exists yet. The constructor of class must be private to prevent other ways of initialization. Also Singleton must be carefully used in multi-threaded applications because in one point of time, the two threads may create two different instances (which violates singleton pattern).
Let's start from not thread-safe implementation.
This is basic implementation and not thread-safe. The two different threads can evaluated the condition
Simple thread-safe implementation is situated below.
This implementation is thread-safe. Here I used shared object (lockObject) to mark a statement block as critical section via lock keyword. But performance suffers because lock is acquired every time the instance requested.
Let's look at thread-safe without using locks implementation.
In C# static constructors executed (once per AppDomain) only when static member is referenced or an instance of class is created. So here you can see some sort of lazy instantiation.
Let's go toward real-world example.
I didn't want to show you example with log system as almost all books/blogs did it. So I have decided to dive deeper in restaurant's stuff.
Imagine that you're going to restaurant. So you're calling to restaurant to make a reservation. Also you want to reserve table near fountain and near big window. Hostess checking all available tables which satisfies your desires and proposing theirs to you.
So all hostesses must use ONLY ONE a piece of paper, which illustrated all tables in the restaurant and theirs statuses, or any application, which helps with it.
Singleton is really suitable for this functionality.
Restaurant and Table classes:
And here's implementation of singleton pattern - Hostess class:
Source code of Singleton pattern you always can find on github.
Have a nice day ;)
P.S. for more details about Singleton pattern go here.