I. Application of the factory model in development
Interview Questions:
Write a simple calculator.
Code implementation:
Abstract An operation class:
Package COM. qianyan. calcuator; public abstract class operation {// number one private double num1; // number two private double num2; Public double getnum1 () {return num1;} public void setnum1 (double num1) {This. num1 = num1;} public double getnum2 () {return num2;} public void setnum2 (double num2) {This. num2 = num2;} public abstract double getresult ();}
Create a factory:
package com.qianyan.factory;import com.qianyan.calcuator.AddOperation;import com.qianyan.calcuator.Operation;import com.qianyan.calcuator.SubtractOperation;public class OperationFactory {public static Operation getOperation(String oper){if("+".equals(oper))return new AddOperation();else if("-".equals(oper))return new SubtractOperation();elsereturn null;}}
Abstract operation implementation class:
package com.qianyan.calcuator;public class AddOperation extends Operation{@Overridepublic double getResult() {return this.getNum1() + this.getNum2();}}
package com.qianyan.calcuator;public class SubtractOperation extends Operation{@Overridepublic double getResult() {return this.getNum1() - this.getNum2();}}
User class:
Package COM. qianyan. user; import Java. util. producer; import COM. qianyan. calcuator. operation; import COM. qianyan. factory. operationfactory; public class user {public static void main (string [] ARGs) {system. out. println ("---- small C calculator program ----"); input = new calculator (system. in); system. out. println ("Enter the first calculation number:"); string str1 = input. nextline (); system. out. println ("Enter the operator:"); string Signature = input. nextline (); system. out. println ("enter the second calculation number:"); string str2 = input. nextline (); double num1 = double. parsedouble (str1); double num2 = double. parsedouble (str2); Operation opertion = operationfactory. getoperation (operator); opertion. setnum1 (num1); opertion. setnum2 (num2); double result = opertion. getresult (); system. out. println (str1 + struct + str2 + "=" + result );}}
Test results:
---- Small C calculator program ---- enter the first calculation number: 5 enter the operator:-enter the second calculation number: 35-3 = 2.0