我正在实现一个对象缓存:
void cache(String request_type, String request_id, ProcessingStrategy request_strategy)
{
if (no_state(request_strategy) == true)
map.put(request_type, request_strategy);
else
map.put(request_id, request_strategy); //no chance of keyspace collision
}
ProcessingStrategy lookup(String request_type, String request_id)
{
ProcessingStrategy request_strategy = map.get(request_type);
if (request_strategy == null) return map.get(request_id)
else return request_strategy;
}
这种在特定类型的所有请求之间共享实现接口ProcessingStrategy的对象的方案仅在没有在具体类中存储状态的情况下才有效.
如何编写no_state方法?
我正在考虑使用反射来检查是否所有成员字段都是最终的:
for(Field f : request_strategy.getClass().getDeclaredFields())
if(!Modifier.isFinal(f.getModifiers()))
return false;
//even if all fields are final;
//how to check that they are not being initialized with differently in the ProcessingStrategy constructor?