简单工厂模式之代码修改封闭尝试

参考:开放封闭原则,

Main方法:OperaClientMain

package com.factory.simple.main;
import java.util.Scanner;
import com.factory.simple.dao.Operation;
import com.factory.simple.service.SimpleFactory;

public class OperaClientMain {

 /**
  * @param args 简单工厂の运算
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  Scanner scan = new Scanner(System.in);
  System.out.println("请输入数字A :");
  double numberA= scan.nextDouble();
  System.out.println("请输入运算符: OperationAdd,OperationSub");
  String operate =  scan.next();
  System.out.println("请输入数字B :");
  double numberB = scan.nextDouble();
  Operation opera = SimpleFactory.creatOperation(operate);
  opera.setNumberA(numberA);
  opera.setNumberB(numberB);
  System.out.println(numberA+"与 "+numberB+" 运算结果 "+opera.getResult());
 }
}

2 运算工厂类:SimpleFactory

package com.factory.simple.service;
import com.factory.simple.dao.Operation;

public class SimpleFactory {
 
 public static Operation creatOperation(String operate){
  Operation opera = null ;
  /* 这里operator为char类型
  switch(operate){
  case '+' : opera = new OperationAdd();break;
  case '-' : opera = new OperationSub();break;
  case '*' : opera = new OperationMul();break;
  case '/' : opera = new OperationDiv();break;
  default:opera = new Operation();
  }*/
  String optPath = Operation.class.getPackage().getName()+".imp.";
  try { //采用直接实例化的方法,避免了添加一个运算类(如乘法)时,需要对该类进行修改
   Class<?> c = Class.forName(optPath+operate);
   opera = (Operation) c.newInstance();
  } catch (Exception e) {
   opera =  null;
  }
  return opera;
 }
}

3 运算类 父类 也可以写成接口 此处通过继承可以达到避免代码重复 

package com.factory.simple.dao;

public class Operation {
 private double numberA;
 private double numberB;
 public double getNumberA() {
  return numberA;
 }
 public void setNumberA(double numberA) {
  this.numberA = numberA;
 }
 public double getNumberB() {
  return numberB;
 }
 public void setNumberB(double numberB) {
  this.numberB = numberB;
 }
 public double getResult(){
  double result=0;
  return result;
 }
}

4 加法运算类

package com.factory.simple.dao.imp;

import com.factory.simple.dao.Operation;

public class OperationAdd extends Operation {
 public double getResult(){
  
  return this.getNumberA()+this.getNumberB();
 }
}

5.减法运算类OperationSub

package com.factory.simple.dao.imp;

import com.factory.simple.dao.Operation;

public class OperationSub extends Operation {
 public double getResult(){
  return this.getNumberA()-this.getNumberB();
 }
}

 

6.运算示例:

请输入数字A :
11
请输入运算符: OperationAdd,OperationSub
OperationSub
请输入数字B :
3
11.0与 3.0 运算结果 8.0

 

你可能感兴趣的:(简单工厂模式,开闭原则)