I have a view
which takes a DataPresenterStrategy
instance to retrieve the proper text out of some data:
public interface DataPresenterStrategy {
String getDisplayString(Data data);
String getUnit();
}
public class DistanceStrategy implements DataPresenterStrategy {
@Override
public String getDisplayString(Data data) {
return data.getDistance();
}
@Override
public String getUnit() {
return "m";
}
}
public class PowerStrategy implements DataPresenterStrategy {
@Override
public String getDisplayString(Data data) {
return data.getPower();
}
@Override
public String getUnit() {
return "W";
}
}
Based on some enum, I know which DataPresenterStrategy
to create:
enum DataPresenterStrategyType { DISTANCE, POWER }
DataPresenterStrategy toStrategy(StrategyType type) {
switch(type) {
case DISTANCE:
return new DistanceStrategy();
case POWER:
return new PowerStrategy();
}
}
Obviously, this is simplified. In my actual code I have 25 of those Strategy
classes.
Is there a better way to do this DataPresenterStrategy
instance creation?
Usage in views:
public interface DataPresenter {
void setDataPresenterStrategy(DataPresenterStrategy strategy);
}
public class DataView implements DataPresenter {
private DataPresenterStrategy mDataPresenterStrategy;
@Override
public void setDataPresenterStrategy(DataPresenterStrategy strategy) {
mDataPresenterStrategy = strategy;
}
}
public class MyApplication {
private DataPresenter[] mDataPresenters;
public void setDataPresenterStrategy(int dataPresenterIndex, DataPresenterStrategyType type) {
switch (type)
/* (...) */
}
}
setDataPresenterStrategy(int, DataPresenterStrategyType)
is called when a user selects an item from a spinner:
class MyOnItemSelectedListener implements OnItemSelectedListener {
private int mPresenterIndex;
public OnItemSelectedListener(int presenterIndex) {
mPresenterIndex = presenterIndex;
}
void onItemSelected(int which) {
setDataPresenterStrategy(mPresenterIndex, DataPresenterStrategyType.values()[which];
}
}