Difference between Singleton vs Static in Java
These are few differences between static and singleton in Java.
1) Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.
2) One more difference between Singleton and static is, ability to override. Since static methods in Java cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.
3) Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes, because you can pass mock object whenever Singleton is expected, e.g. into constructor or as method arguments.
4) If your requirements needs to maintain state than Singleton pattern is better choice than static class, because
maintaining state in later case is nightmare and leads to subtle bugs.
5) Singleton classes can be lazy loaded if its an heavy object, but static class doesn't have such advantages and always eagerly loaded.
6) Many Dependency Injection framework manages Singleton quite well e.g. Spring, which makes using them very easy.
No comments:
Post a Comment