1. Create an interface for the operation
Public Interface operation { // provides a method for calculating two numbers double getresult (double num1, Double num2);}
2. Create a corresponding subtraction four implementation class
public class addition implements operation {// Addition @Override public double getresult (double num1, double num2) { return num1+NUM2; }}
public class minus implements operation {// subtraction @Override public double getresult (double num1, double num2) { return num1-NUM2; }}
public class multiplication implements operation {// multiplication @Override public double getresult (double num1, double num2) { return num1*NUM2; }}
Public class Implements Operation {// Division @Override publicdouble GetResult ( Doubledouble num2) { return num1/num2; }}
3. Create a factory class
Public classoperationfactory {//factory class for computers /** Factory mode is the model of our most commonly used instanced objects! * Replace new! with a factory method * Although the amount of code has not decreased but increased the scalability of the program! */ Public StaticOperation Getoperation (String o) {operation Operation=NULL;// polymorphic Switch(o) { Case"+": Operation=Newaddition (); Break; Case"-": Operation=Newminus (); Break; Case"*": Operation=Newmultiplication (); Break; Case"/": Operation=NewDivision (); Break; } returnoperation; }}
4. Create test class Run test results
Public classFactorytest { Public Static voidMain (string[] args) {Scanner Scanner=NewScanner (system.in); System.out.println ("Please enter the first number:"); DoubleNUM1 =Scanner.nextint (); System.out.println ("Please enter operator:"); String Operation=Scanner.next (); System.out.println ("Please enter a second number:"); Doublenum2 =Scanner.nextint (); //create an instance object of an operationOperation o =Operationfactory.getoperation (operation); //Output ResultsSystem.out.println (O.getresult (NUM1, num2)); }}
Simple Factory mode Implementation subtraction method