/** * Created by hero on 17-2-17. */ publicinterfaceOperation { doublegetResult(double a, double b); }
1 2 3 4 5 6 7 8 9 10 11
package factory.method;
/** * Created by hero on 17-2-17. */ publicclassAddimplementsOperation { publicdoublegetResult(double a, double b) { return a + b; } }
1 2 3 4 5 6 7 8 9 10 11
package factory.method;
/** * Created by hero on 17-2-17. */ publicclassMultiplicationimplementsOperation { publicdoublegetResult(double a, double b) { return a * b; } }
1 2 3 4 5 6 7 8 9
package factory.method;
/** * Created by hero on 17-2-17. */ publicinterfaceOperationFactory { Operation createOperation(); }
1 2 3 4 5 6 7 8 9 10 11
package factory.method;
/** * Created by hero on 17-2-17. */ publicclassAddFactoryimplementsOperationFactory { public Operation createOperation() { returnnewAdd(); } }
1 2 3 4 5 6 7 8 9 10 11
package factory.method;
/** * Created by hero on 17-2-17. */ publicclassMultiplicationFactoryimplementsOperationFactory { public Operation createOperation() { returnnewMultiplication(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13
package factory.method;
/** * Created by hero on 17-2-17. */ publicclassMain { publicstaticvoidmain(String[] args) { OperationFactoryfactory=newAddFactory(); //若要改为乘法,只需修改此一处 Operationoperation= factory.createOperation(); System.out.println(operation.getResult(1, 2)); } }