我有两个相关的枚举.
Enum1:
public enum HttpMethodName { GET,POST,PUT,DELETE; }
Enum2:
public enum ProtocolOperation { CREATE(1),RETRIEVE(2),UPDATE(3),DELETE(4),NOTIFY(5); private BigInteger operationId; public BigInteger getOperationId() { return operationId; } private ProtocolOperation(int operationId) { this.operationId = BigInteger.valueOf(operationId); } }
枚举值的映射为:
Create--> POST Retrieve--> GET Update--> PUT Delete--> DELETE Notify---> POST
所以在值之间有一对一的映射,除了POST事件之外,它可以根据条件创建或通知两个值.
我正在考虑将映射保持为列表:
public enum HttpMethodName { POST(new List(ProtocolOperation.CREATE,ProtocolOperation.NOTIFY)),GET ( new List(ProtocolOperation.RETRIEVE) ),PUT (new List(ProtocolOperation.UPDATE),DELETE(new List(ProtocolOperation.DELETE) ; List<ProtocolOperation > ops; HttpMethodName (List<ProtocolOperation> ops) { this.ops = ops; } }
有更好的做法吗
编辑:
我将要从HttpMethodName< ---->映射两种方式ProtocolOperation
解决方法
你为什么发现目前的方法不能令人满意?
没有你的关注的知识,我只能建议删除样板:
import static ProtocolOperation.*; public enum HttpMethodName { GET(RETRIEVE),POST(CREATE,NOTIFY),PUT(UPDATE),DELETE(ProtocolOperation.DELETE); final List<ProtocolOperation> ops; HttpMethodName(ProtocolOperation... ops) { this.ops = Collections.unmodifiableList(Arrays.asList(ops)); } }
UPD:
如果要以两种方式进行映射,则首先将协议操作映射到HttpMethodName(因为不需要列表),并在MttpMethodName中创建一个简单的搜索方法是有意义的:
public enum ProtocolOperation { CREATE(1,HttpMethodName.POST),RETRIEVE(2,HttpMethodName.GET),UPDATE(3,HttpMethodName.PUT),DELETE(4,HttpMethodName.DELETE),NOTIFY(5,HttpMethodName.POST); private BigInteger operationId; private HttpMethodName methodName; public BigInteger getOperationId() { return operationId; } public HttpMethodName getMethodName() { return methodName; } private ProtocolOperation(int operationId,HttpMethodName httpMethodName) { this.methodName = httpMethodName; this.operationId = BigInteger.valueOf(operationId); } } public enum HttpMethodName { GET,DELETE; List<ProtocolOperation> getProtocolOperations() { List<ProtocolOperation> ops = new ArrayList<ProtocolOperation>(2); for (ProtocolOperation op : ProtocolOperation.values()) { if (op.getMethodName() == this) { ops.add(op); } } return ops; } }
由于您具有常量和少量的值,因此您不需要在HttpMethodName中创建最终的静态映射,以提供向后映射,线性搜索对于您的情况来说足够快.