+ 1

What is Singleton? and how can we use it in three tier architecture in c#?

What is Singleton? and how can we use it in three tier architecture in c#?

8th Feb 2018, 11:43 AM
Vishwanath Patil
Vishwanath Patil - avatar
4 odpowiedzi
+ 2
A singleton is a class that, by design, is guaranteed to have either 0 or 1 instances, 0 if it isn't yet in use. On first use the singleton class will create an instance, that instance is then used by everyone else as well. How it works is not that difficult. In most languages you'd make the constructor private to prevent others form making objects. You then have a static pointer or reference to yourself and a static "GetInstance" method that: - checks if the pointer or reference is null, if so make a new object and store it - return the pointer/reference Using this pointer/reference you can then access the normal methods. I have sometimes used singletons for logging classes. Wherever you are, you simply call: Logger.GetInstance().log(... your data here...) Everybody is now guaranteed to use the same object. What I dislike about singletons is that they are often used without good reason. Most of the times I see them it's really a design problem... And sometimes also a problem for testability. In my opinion, dependency injection is often a cleaner solution when compared to misuse of singletons. Does that help?
8th Feb 2018, 11:15 PM
Freddy
0
thank you Freddy !
12th Feb 2018, 12:31 PM
Vishwanath Patil
Vishwanath Patil - avatar
0
use of singleton is to prevent multiple instance of same class if we create multiple objects of same class then memory is reserved for each objects and that is not pure coding ...
12th Feb 2018, 12:36 PM
Vishwanath Patil
Vishwanath Patil - avatar
0
Well, yes and no. Preventing multiple copies of the same object can be done using a singleton construction, the downside however is that *any* class in your project can use it. For a logger class that's OK (it's what you want, really), but most of the times you shouldn't want that. I usually have one place where (most of) my objects are created and use dependency injection to selectively hand out references. Now only the classes that should work with a given other class have the means to do so. Designs with lots of singletons are a disaster for maintenance! Have a look at my dependency injection code examples. That's much beter than the highly overrated singleton pattern.
12th Feb 2018, 1:16 PM
Freddy