3

Let's say I have the following Java code:

public class ObjectConsumer implements Consumer<Object> {
    @Override
    public void accept(Object o) {
        System.out.println("Accepted " + o);
    }
}

Example singleton implementation:

public enum ObjectConsumer implements Consumer<Object> {
    INSTANCE;

    @Override
    public void accept(Object o) {
        System.out.println("Accepted " + o)
    }
}

The class above has got no instance specific data (fields). Is it okay to make it a singleton? Is there anything I should keep an eye on when doing this or are there any clear drawbacks?

  • 2
    What do you mean "okay"? Why do you want to make it a singleton in the first place? – JacquesB Jun 28 '17 at 13:04
  • 3
    @Mibac: If you only need one instance then just create one instance. If you don't have any instance specific data, I don't see why you would need to use a singleton pattern? – JacquesB Jun 28 '17 at 13:13
  • 1
    Design patterns don't exist to be used whenever you can, but to help you get it right when you need them. – Jacob Raihle Jun 28 '17 at 13:22
  • 1
    @TheCatWhisperer Java doesn't have free functions – Caleth Jun 28 '17 at 15:22
  • 1
    Why not make the method static? It seems to be appropriate here since it's a stateless function – BlueWizard Jun 28 '17 at 21:30
12

No, it is not correct to make a class a Singleton, just because it has no instance data.

When a class is a Singleton, this gives a very specific message to the maintainers of the software:

There must only ever be one instance of this class. Within the domain of the application, it does not make sense to have multiple instances of this class.

The simple fact that multiple instances would always behave identically, because they don't have instance data, or that you currently only need one instance (while having more is not a logical impossibility), is not enough of a reason to make the class a Singleton.

|improve this answer|||||
  • As an additional remark, a class with no instance specific data may be instantiated across multiple threads and destroyed after use. Converting it into a singleton would cause havoc, since thread B might try to use the singleton after thread A has used it. – Akshat Mahajan Jun 28 '17 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.