This blog is about Java development and describes in detail the most important topics.
Posts with tag «singleton»
The singleton design pattern is one of the most inappropriately used patterns. In this article we review several implementations of a singleton that work correctly in multithreaded environment, with serialization and cloning tasks and even with reflection attacks.
What for you can use singleton The singleton pattern is used when there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point or when the single instance should be extensible by sub-classes, and clients should be able to use an extended instance without modifying their code. Distinction from static class JDK has examples of both singleton and static, on the one hand java.lang.Math is a final class with static methods, on the other hand java.lang.Runtime is a singleton class. Advantages of singleton If your need to maintain state than singleton pattern is better choice than static class, because maintaining state in static class leads to bugs, especially in concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads. Singleton class can be lazy loaded if its a heavy object, but static class doesn't have such advantages and always eagerly loaded. With singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations. Since static methods in Java cannot be overridden, they lead to infl Read more