Background requirements:
Simulate a simple calculator.
UML class:
illustrate:
The abstract class AbstractOperation has an abstract method getResult and two member variables. Addition, subtraction, multiplication and division respectively inherit AbstractOperation and implement the getResult method. OperationFactory is a simple factory method that instantiates different subclasses based on input parameters.
demo:
AbstractOperation class:
1 public abstract class AbstractOperation { 2 3 private Double firstNumber; 4 private Double secondNumber; 5 6 public abstract Double getResult() throws Exception; 7 8 public Double getFirstNumber() { 9 return firstNumber; 10 } 11 12 public void setFirstNumber(Double firstNumber) { 13 this.firstNumber = firstNumber; 14 } 15 16 public Double getSecondNumber() { 17 return secondNumber; 18 } 19 20 public void setSecondNumber(Double secondNumber) { 21 this.secondNumber = secondNumber; 22 } 23 }
Addition class OperationAdd:
1 public class OperationAdd extends AbstractOperation { 2 @Override 3 public Double getResult() { 4 return getFirstNumber() + getSecondNumber(); 5 } 6 }
Subtraction class OperationSub:
1 public class OperationSub extends AbstractOperation { 2 @Override 3 public Double getResult() { 4 return getFirstNumber() - getSecondNumber(); 5 } 6 }
Simple factory class OperationFactory:
1 public class OperationFactory { 2 3 public static AbstractOperation createOperation(String operate){ 4 AbstractOperation operation = null; 5 6 switch (operate){ 7 case "+":operation = new OperationAdd();break; 8 case "-":operation = new OperationSub();break; 9 default:break; 10 } 11 return operation; 12 } 13 }
Client test class:
1 public class Main { 2 3 public static void main(String[] args) throws Exception { 4 5 AbstractOperation operation = 6 OperationFactory.createOperation("+"); 7 operation.setFirstNumber(10d); 8 operation.setSecondNumber(20d); 9 System.out.println(operation.getResult()); 10 11 } 12 }
Summarize:
The simple factory pattern is suitable for situations where a large number of instances of the same type (same parent class or implements the same interface) need to be created