简单工厂将业务逻辑部分和界面逻辑部分分离开来,降低了界面逻辑和业务逻辑的耦合度,符合面向对象迪米特法则。下面以一个加法减法运算器为例,各位读者可以自行按照这种设计方式设计出一个小小的运算器。
1、业务逻辑
1.1、父类Operation
1 package com.designmode.simplefactory; 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.simplefactory; 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.simplefactory; 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、生成对象工厂
1 package com.designmode.simplefactory; 2 3 public class OperationFactory { 4 5 /** 6 * 创建对象工厂 7 * @param operate 运算符 8 * @return 运算对象 9 */ 10 public static Operation createOperation(String operate){ 11 Operation operation = null; 12 switch (operate) { 13 case "+": 14 operation = new AddOperation(); 15 break; 16 case "-": 17 operation = new SunOperation(); 18 break; 19 default: 20 System.out.println("请输入正确的运算符!"); 21 break; 22 } 23 return operation; 24 } 25 }
2、页面逻辑
1 package com.designmode.simplefactory; 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 Operation operation = OperationFactory.createOperation(operate); // 生成运算对象 18 operation.setValue(numberA, numberB); // 设置numberA与numberB的值 19 int result = operation.getResult(); // 获取运算结果 20 System.out.println(numberA+operate+numberB+"="+result); // 打印运算结果 21 } 22 }