Dealing with enums implementing common interface (iterate, deserialize)

602 Views Asked by At

I have an Android application that loads a data from web sources and displays it. I organized each API method those sources support in enum constants split per source. Let's say, SourceA provides Sport and Weather data and SourceB provides Stock and News data.

public enum ServiceA implements ServiceMethod {
    GET_SPORT(...) {...}, 
    GET_WEATHER(...) {...};
    ...
}

public enum ServiceB implements ServiceMethod {
    GET_STOCK(...) {...}, 
    GET_NEWS(...) {...};
    ...
}

Each enum class also has private members to deal with service API (different API for differenc sources)

And a variable of ServiceMethod

ServiceMethod method;
... // initializing
String cleanAndFancyData = method.queryData(); // e.g.

No I need to store user history, so I have to serialize and deserialize ServiceMethod variable and also enumerate all constants from all enums implementing this interface. The serialization looks simple and is out of question.

Now I just manually iterate over enums:

Collection<ServiceMethod> allMethods = new ArrayList<ServiceMethod>();
allMethods.addAll(EnumSet.allOf(ServiceA.class));
allMethods.addAll(EnumSet.allOf(ServiceB.class));

Is there a cleaner, nicer way for this? Or is my approach completely wrong? Also, any way to ensure that all ServiceMethod have unique names (across all enums)?

1

There are 1 best solutions below

0
On

You may be able to use the strategy pattern to combine ServiceA and ServiceB into a single Service.