枚举对象应该是无状态的吗? [英] Should enum objects be stateless?

查看:114
本文介绍了枚举对象应该是无状态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:



目前,我正在创建一个具有Operations(具有使用策略模式的变体的枚举)的REST服务。

  public enum Operation {

DO_THIS(){
public Result doSomething ){
}
},
//其他操作去这里
;

public abstract Result doSomething(Object theData);

}

现在我想收集有关操作频率的数据被调用,并且成功的频率等等。



我可以在使用枚举实例时外部保存状态,但似乎状态应该保存在操作中因为操作应该包含它自己的状态。



现在我的一般问题是:



是一个有条件的枚举实例(并发问题除外)一个糟糕的设计?

解决方案

我认为它违反了原则惊讶。



人们期望枚举的常见用法是原始设计的 - 作为常量或令牌,而不是具有状态的通用类。


As by design an enum constant in java is a singleton, and for sake of concurrent usage I normally create stateless enum instances and use method parameters to inject the data as needed.

Example:

Currently I am creating a REST service which has Operations (implemented as an enum using a variant of the strategy pattern).

public enum Operation {

  DO_THIS() {
    public Result doSomething(Object theData) {
    }
  } ,
  // Other Operations go here
  ;

  public abstract Result doSomething(Object theData);

}

Now I want to collect data about how often an operation has been called and how often it succeeded and the like.

I could save the state externally when using the enum instance but it rather seems that the state should be saved in the Operation as the operation should contain it's own state.

Now my general question is:

Is a stateful enum instance (besides from concurrency issues) a bad design?

解决方案

I think it violates the Principle of Least Astonishment.

People expect the common usage of enums as they were originally designed - as constants or tokens, and not as general purpose classes with state.

这篇关于枚举对象应该是无状态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆