javaoopsingletonimmutabilitysingle-instance

Is it bad to use Singletons for immutable no-argument classes?


I am working on a small Java Project right now, and while doing so there where multiple classes created which represent some kind of Constant behaviour for example use as default return value for other methods.

Now what all these have in common is, that they are completely immutable and that they only have a no argument constructor. This means that creating multiple instances of that class will always result in identical objects.

Is it better to just create a new instance everytime these classes are used or is this a acceptable case to use the singelton pattern?


Solution

  • Let's consider pros and cons of singleton assuming you have a small project and immutable classes that are used as default return values.

    Pros of singleton in this case:

    Cons:

    So there is no single right answer I think, it depends on how you see the evolution of your project in future.