服务类应该是java中的单例吗?

Jyo*_*rup 10 java design-patterns

在设计服务类时,它应该是java中的单例吗?一般来说DAO是单例的,所以调用Service类也应该是单例吗?

Sti*_*ens 8

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

  • @Jyotirup:这是错误的,你混淆了线程和对象......同步是一个不同的主题. (6认同)
  • @Jyotirup正确使用单例不会影响性能(如果有任何改进的话) (3认同)
  • @thinksteep,我的感觉是,单身人士应该是无国籍的,并且在线安全. (2认同)

DwB*_*DwB 0

如果你开发它们,单例是不好的。如果您使用依赖注入,请让 DI 容器处理 Service 对象的单例性质。如果您不使用依赖注入,请使用静态方法而不是单例。

不好的经典例子:

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.
Run Code Online (Sandbox Code Playgroud)

更好地实现上述内容:

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(...);
Run Code Online (Sandbox Code Playgroud)

如果您有一个具有具体实现的服务接口,请使用依赖注入框架来注入实现(DI 框架包括:spring 和 guice)。

编辑:如果我使用 spring,我会选择单例范围(默认)。