以下以创建计算器为例
第一步:先创建Operation实体类
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;
}
}
第二步:实现各运算类
现以加法运算类为例
public class OperationAdd extends Operation{
//重写getResult()函数
public double getResult(){
double result = 0;
result = getNumberA() + getNumberB();
return result;
}
}
第三步:编写工厂类
public classs OperationFactory{
public static Operation createOperation(String operate){
Operation ope = null;
Switch(operate){//根据不同的运算符,实例对应的对象
case "+" :
ope = new OperationAdd;
break;
}
return ope;
}
}
第四步:创建测试类
public static void main(String[] args){
Operation opera;
opera = OperationFactory.createOperation("+");
opera.setNumberA(1);
opera.setNumberB(2);
double result = opera.getResult();
System.out.println(result);
}
输出结果:
工厂模式是为松耦合,模块化,利用继承 多态做到功能分离,更利于以后的拓展