##Simple Factory Mode##
What is factory mode
**Simple factory mode**: Whoever you want to instance, and whether you want to add instantiated objects in the future, should consider using a separate class to create this instance, which is the factory.
Step One
public class OperationObject { private double _numberA = 0; private double _numberB = 0; public double get_numberA() { return _numberA; } public void set_numberA(double _numberA) { this._numberA = _numberA; } public double get_numberB() { return _numberB; } public void set_numberB(double _numberB) { this._numberB = _numberB; } public double getResult(){ double result = 0; return result; } }
Step 2:
//addition public class OperationAdd extends OperationObject { public double getResult(){ double result = 0; result = get_numberA()+get_numberB(); return result; } } //addition public class OperationDiv extends OperationObject{ public double getResult() { double result = 0; if (get_numberB() == 0){ try { throw new Exception("Divisor can not Be zero"); } catch (Exception e) { e.printStackTrace(); } } result = get_numberA() / get_numberB(); return result; } } //multiplication public class OperationMul extends OperationObject { public double getResult(){ double result = 0; result = get_numberA() * get_numberB(); return result; } } //division public class OperationSub extends OperationObject { public double getResult(){ double result = 0; result = get_numberA() - get_numberB(); return result; } }
Step Three
//Simple factory mode: Whoever you want to instantiate, and whether you want to add instantiated objects in the future, should consider using a separate class to create this instance. This is the factory. //In a word, a factory contains a bunch of objects that need instances public class OperationFactory { public static OperationObject createOperation(String operation){ //Responsible for production addition, subtraction, multiplication and division OperationObject operationObject = null; switch (operation){ case "+": operationObject = new OperationAdd(); break; case "-": operationObject = new OperationSub(); break; case "*": operationObject = new OperationMul(); break; case "/": operationObject = new OperationDiv(); break; } return operationObject; } }
Step 4
public class factoryDesign { public static void main(String[] args) { //The type of calculation required by the instance OperationObject operationObject = OperationFactory.createOperation("-"); operationObject.set_numberA(2); operationObject.set_numberB(4); double result = operationObject.getResult(); System.out.println(result); } }
The above content is personal notes after learning big talk design mode, do not like to spray.