Port of schuchert.wikispaces.com


Factory Method Exercise Hints

Factory Method Exercise Hints

The eecute method in RpnCalculator violates the Single Responsibility Principle. It does different things that change for different reasons.

Breaking these two things into separate responsibilities, e.g., methods, cleans up the code.

Once you’ve made this improvement, a next step might be to pull the location responsibility into its own class.

This becomes a factory for operators. The RpnCalculator deletages the lookup of a operator name to the factory, then sends execute to an operator.

For this to work easily, it helps that we’ve already introduced the Strategy Pattern in the from of a Operator interface.

A good end result for RpnCalculator::execute could be:

public void execute(String operatorName) {
    Operator op = factory.operatorFor(operatorName);
    op.execute(values);
}

Things to do:

As a bonus, you can use a library like Class Graph to dynamically find the classes. Later versions of this project do that.


Comments

" Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.