Search code examples
javasingletonstatic-class

Singleton and static classes case study


It was already asked what's the difference between singleton and static class. However, knowing the difference, I still feel confused every time I need to chose.

So for myself I defined two different cases - I'm using singletones mainly for POJO classes(in java) if there should be only one instance of this class(which is very rarely) and static classes for all service classes(which occur very often).

For example, in my application I need to store messages(I have a serializable class Message), write them into a file, read from a file and access during the runtime. I don't see any reason to use singleton here, static class is just okay. The only static class is MessageStorage which has 3 functions - read, write and getMessages and also one static private arraylist of messages.

Is this approach reasonable and if not, what's its problem?


Solution

  • The two main reasons for using a "singleton" in Java are:

    1) So some storage can be associated with an otherwise "static" class.

    2) Where you may have multiple "singletons" for different subclasses (or interface implementations) of a given service, and the singleton is passed as a way of identifying which specific service to employ.

    Of course, instead of #1 you can use static fields of a "static" class to contain the data, but it's often more convenient (and, in many cases, more efficient) to have a single instance of the subject class to contain the data, vs multiple static members which are instances of other classes.

    And, re #2, there are a number of cases in the JDK of a single class implementing, in effect, multiple "singletons", in the guise of defining "constants". (Eg, java.awt.font.TextAttribute.)

    In general, the motivation to have singletons is less in Java than in C-based languages, since Java does implement true class-associated (and class-protected) static data, vs the vaguely disguised (if disguised at all) global statics used in the C languages, and so one can simply have multiple static fields in a class vs the need to have a "central" object to contain the fields in the C languages.