mercredi 9 septembre 2015

getting correct objects from string parameter in factory

I've been trying to figure out if theres a way to pass a string to a factory or constructor and create the correct object without having to map the string to an object, or without having a bunch of if/else statements or switch statements.

Keep in mind, this is a simple example so I can apply what I learn to more complicated situations in web apps, etc.

let's take a simple calculator app, written in JAVA, as an example


assuming this is command line, and a person can pass in 3 values

- first number
- math operation (+ , - , / , x)
- second number

and we have an interface

public interface ArithmeticOperation {
  public double performMathOperation(double firstNum, double secondNum);
}

with 4 classes that implement it

public class AdditionOperation implements ArithmeticOperation {
  public double performMathOperation(double firstNum, double secondNum) {
    return firstNum + secondNum;
  }
}

// public class Subtraction operation returns firstNum - secondNum
// etc...

and we have our actual Calculator class and UserInput class

public class UserInput {
  public UserInput(double firstNum, double secondNum, String operation) {
    this.firstNum = firstNum;
    // etc...
  }
}
public class Calculator {
  public UserInput getInput() {
    // get user input, and return it as a UserInput object
    // return a UserInput object
  } 
  public performOperation() {
    UserInput uInput = getInput();
    double answer = ArithmeticOperationFactory
      .getSpecificOperation(uInput.operation)
      .performMathOperation(uInput.firstNum, uInput.secondNum);
    // send answer back to user
  }
}

finally, the place where the question mostly revolves around, the factory

public class ArithmeticOperationFactory {

  public static ArithmeticOperation getSpecificOperation(String operation) {
    // what possibilities are here?
    // I don't want a map that maps strings to objects
    // I don't want if/else or switch statements
    // is there another way?

  }
}

also, if theres a better way to architect a system like this or a design pattern that can be applied, please share. I'm really trying to learn some good object oriented design

Aucun commentaire:

Enregistrer un commentaire