工厂模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到了子类。
1、业务逻辑
1.1、父类Operation
package com.designmode.factory; public abstract class Operation { protected int numberA;
protected int numberB; public void setValue(int numberA,int numberB){
this.numberA=numberA;
this.numberB=numberB;
} public abstract int getResult();
}
1.2、加法类AddOperation
package com.designmode.factory; public class AddOperation extends Operation { @Override
public int getResult() {
// TODO Auto-generated method stub
return this.numberA+this.numberB;
} }
1.3、减法类SubOperation
package com.designmode.factory; public class SunOperation extends Operation { @Override
public int getResult() {
// TODO Auto-generated method stub
return this.numberA-numberB;
} }
1.4、工厂父类OperationFactory
package com.designmode.factory; public interface OperationFactory { /**
* 创建对象工程
* @param operate
* @return
*/
Operation createOperation(String operate); }
1.5、生成加法运算对象工厂AddOperation
package com.designmode.factory; public class AddFactory implements OperationFactory { @Override
public Operation createOperation(String operate) {
// TODO Auto-generated method stub
return new AddOperation();
} }
1.6、生成减法运算对象工厂SubOperation
package com.designmode.factory; public class SubFactory implements OperationFactory { @Override
public Operation createOperation(String operate) {
// TODO Auto-generated method stub
return new SunOperation();
} }
2、页面逻辑
package com.designmode.factory; import java.util.Scanner; public class OperationTest { @SuppressWarnings("resource")
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("请您输入第一个数字:");
int numberA = Integer.parseInt(reader.nextLine());
System.out.print("请您输入运算符:");
String operate = reader.nextLine();
System.out.print("请您输入第二个数字:");
int numberB = Integer.parseInt(reader.nextLine()); OperationFactory operationFactory = null;
switch (operate) {
case "+":
operationFactory = new AddFactory();
break;
case "-":
operationFactory = new SubFactory();
break;
default:
System.out.println("你输入错误,请重新输入!");
break;
}
Operation operation = operationFactory.createOperation(operate); // 生成运算对象
operation.setValue(numberA, numberB); // 设置numberA与numberB的值
int result = operation.getResult(); // 获取运算结果
System.out.println(numberA+operate+numberB+"="+result); // 打印运算结果
}
}