Jyotirup
Jyotirup

Reputation: 2920

Should a Service class be singleton in java?

While designing a service class should it be singleton in java? Generally DAO is made singleton, so should the calling Service class be made singleton also?

Upvotes: 13

Views: 16002

Answers (3)

DwB
DwB

Reputation: 38300

Singletons are bad, if you develop them. If you are using dependency injection, let the DI container handle the singleton nature of your Service object. If you are not using dependency injection, use a static method instead of a singleton.

Classic example of bad:

public class HootUtility // singleton because developer was a goofball.
{
   ...
   public void blammy(...) { ... }
   public HootUtility getInstance() { ... }
}

... somewhere in the code.

HootUtility.getInstance().blammy(...);  // This is silly.

Better implementation of the above:

public class HootUtility // Not a singleton because I am not a ______. (fill in the blank as you see fit)
{
  // You can limit instantiation but never prevent instantiation.
  // google "java reflection" for details.
  private HootUtility()
  {
    throw new UnsuppotedOperationException();
  }

  public static void blammy(...) { ... }
}

... somewhere in the code.

HootUtility.blammy(...);

If you have a service interface that has an concrete implementation, use a dependency injection framework to inject the implementation (DI frameworks include: spring and guice).

Edit: If I was using spring, I would choose singleton scope (the default).

Upvotes: -1

Stan Kurilin
Stan Kurilin

Reputation: 15792

No

Actually I believe you shouldn't care about it while design. Like @DwB mentioned DI framework should do this job. Furthermore I believe no scope ("prototype") should be default and I don't see anything bad if somebody will create it itself. Also that issue can be simplified by modularization and separating service interface and implementation like best practices told as to do.

Upvotes: 0

Stijn Geukens
Stijn Geukens

Reputation: 15628

IMHO yes, services should not hold state and should therefore be made singleton.

Upvotes: 14

Related Questions