I'm trying to write a basic sample of interface implementation in java. The idea is to select an instance depending on a keyword. Here is an example:
I have a basic Action
interface which declares a method invoke
I wrote two different implementations of the interface: ActionOpen
and ActionClose
which implements the method invoke
and have a static method getKeyword()
which returns the keyword associated with object
Then I wrote a factory that returns me the appropriate action instance depending on a keyword.
// Action interface
public interface Action {
void invoke();
}
// Action implementations
public class ActionOpen implements Action {
public static String getKeyword() {
return "open";
}
@Override
public void invoke() {
// ...
}
}
public class ActionClose implements Action {
public static String getKeyword() {
return "close";
}
@Override
public void invoke() {
// ...
}
}
// Action factory
public class ActionFactory {
public static Action getInstance(String action) {
if (ActionOpen.getKeyword().equals(action)) return new ActionOpen();
if (ActionClose.getKeyword().equals(action)) return new ActionClose();
return null;
}
}
I'm not happy with the serie of "if" in ActionFactory
because it's not dynamic and I'll have to add new "if" in that factory everytime I create new action classes (for instance if I want to create a "save" action)
It would be better if action classes could register themselves in the factory automatically. I tried this using a static{ }
block in order to do this, but unfortunately static block is not evaluated until I instantiate the action class (or if the class is abstract).
I couldn't find a design pattern that resolves such situation. Any idea ?