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