I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?
What would be the difference between implementing this class as a singleton and just using static
methods?
What would the effect of thousands of users accessing this object/these methods be?
I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.
Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism. Bill Pugh implementation is most widely used approach for singleton classes.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .
Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
While we are using multithreading access to a singleton instance can be performed from various threads it could be a problem while constructing singleton instances. If you are in Singleton::Instance() and receive an interrupt, invoke Singleton::Instance() from another thread, you can see how you'd get into trouble.
Infact instead of singleton you can make the methods static
.
Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.
discussion on Singleton vs Static methods
is here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With