简体   繁体   中英

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?

恕我直言,服务不应该保持状态,因此应该成为单身人士。

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM