Wednesday, October 12, 2016

Difference between Singleton Pattern vs Static Class in Java

If your class don't maintain any state then use static class over singleton.

If your requirement needs to maintain state then Singleton pattern is the better choice because in concurrent environment static class could lead subtle race condition.

In the case of a heavy object, we can lazily load the singleton class but static class alway eagerly loaded.

Static class provide better  performance than Singleton pattern because static methods are bonded on compile time.

java.lang.Math is an example of static class.
java.lang.Runtime is an example of Singleton class.

No comments:

Post a Comment