W zależności od komendy jaką otrzyma fabryka, wypluje inny obiekt. Przykład:
public class MyFactory() {
Map<ActionEnum, Object> objects = new HashMap<>();
public MyFactory(... args ...) {
objects.put(ActionEnum.RUN, new RunObject( ... args ... );
objects.put(ActionEnum.STOP), new StopObject( ... args ...;
objects.put(ActionEnum.WALK, new WalkObject(... args ...);
}
public createObj(ActionEnum action) {
return objects.get(action);
}
}
Wada polega na tym, że niepotrebnie initializuje wszystkie możliwe obiekty, jak mogę potrzebować tylko jednego.
Jakbyście to zrobili? Może być tak?
public class MyFactory() {
Map<ActionEnum, Supplier<ActionObject>> objects = new HashMap<>();
public MyFactory(... args ...) {
objects.put(ActionEnum.RUN, new Supplier<ActionObject>( () -> new RunObject( ... args ... )));
objects.put(ActionEnum.STOP), new Supplier<ActionObject>( () -> new StopObject( ... args ...)));
objects.put(ActionEnum.WALK, new Supplier<ActionObject>( () -> new WalkObject(... args ...)));
}
public ActionObject createObj(ActionEnum action) {
return objects.get(action).get();
}
}