最基本的计算器功能也可以通过工厂模式实现
用到了继承和多态
抽出一个主类运算类,为了符合开闭原则,对修改关闭,对扩展开放
在该类中定义两个做运算的变量A和B
提供一个etResult方法
新建四个算术运算类继承运算类,重写getResult方法,根据自己的类型返回需要的结果
重写Result方法会覆盖父类的Result方法,调用时会调用重写后的方法(用到了继承)
package com.bjsxt.operation;
/**
* 运算类
*
* @author Administrator
*
*/
public class Operation {
protected Double Number1;
protected Double Number2;
public Double getNumber1() {
return Number1;
}
public void setNumber1(Double number1) {
Number1 = number1;
}
public Double getNumber2() {
return Number2;
}
public void setNumber2(Double number2) {
Number2 = number2;
}
public Double getResult() {
return 0.0;
}
}
/**
* 加法运算类
*
* @author Administrator
*
*/
public class OperationAdd extends Operation {
public Double getResult() {
return this.Number1 + this.Number2;
}
}
/**
* 除法运算类
*
* @author Administrator
*
*/
public class OperationDiv extends Operation {
public Double getResult() {
return this.Number1 / this.Number2;
}
}
/**
* 乘法运算类
*
* @author Administrator
*
*/
public class OperationMul extends Operation {
public Double getResult() {
return this.Number1 * this.Number2;
}
}
/**
* 减法运算类
* @author Administrator
*
*/
public class OperationSub extends Operation {
public Double getResult() {
return this.Number1 - this.Number2;
}
}
下面准备工厂对象
工厂对象中提供一个静态方法,返回值类型是运算类,要求传入一个字符串参数
在方法中对该参数进行判断,返回不同的运算类对象,因为返回值类型是运算类,所以该类的所有子类都可以进行返回
/**
* 计算工厂类
*
* @author Administrator
*
*/
public class OperationFactory {
/**
* 返回计算工厂类对象,因为返回值类型用的是父类,所以运算类下所有的子类都可以被实例化
*
* @param Typeid
* @return
* @throws Exception
*/
public static Operation getOperation(Character Typeid) throws Exception {
Operation oper = null;
switch (Typeid) {
case '+':
oper = new OperationAdd();
break;
case '-':
oper = new OperationSub();
break;
case '*':
oper = new OperationMul();
break;
case '/':
oper = new OperationDiv();
break;
default:
throw new Exception("没有该运算符");
}
return oper;
}
这就是一个简单的工厂案例了,谢谢