大话设计模式1 简单工厂模式 的java代码实现

时间:2021-08-22 21:48:26

首先是Operation抽象类:

package yx.designpattern.simpleFactory;

abstract class Operation {
public double number1;
public double number2;

public double getNumber1() {
return number1;
}
public void setNumber1(double number1) {
this.number1 = number1;
}
public double getNumber2() {
return number2;
}
public void setNumber2(double number2) {
this.number2 = number2;
}

public abstract double getResult() throws Exception;

}

继承Operation的加法类:OperationAdd

package yx.designpattern.simpleFactory;

public class OperationAdd extends Operation {

@Override
public double getResult() {
return number1+number2;
}

}

继承Operation的减法类:OperationSub

package yx.designpattern.simpleFactory;

public class OperationSub extends Operation {

@Override
public double getResult() {
return number1-number2;
}

}

继承Operation的乘法类:OperationMul


package yx.designpattern.simpleFactory;

public class OperationMul extends Operation {

@Override
public double getResult() {
return number1*number2;
}

}


继承Operation的除法类:OperationDiv:

package yx.designpattern.simpleFactory;

public class OperationDiv extends Operation {

@Override
public double getResult() throws Exception {
if(number2==0){
throw new Exception("除数不能为0");
}
return number1/number2;
}

}

生成Operation的工厂类:OperationFactory

package yx.designpattern.simpleFactory;

public class OperationFactory {
public static Operation createOperation(char operation){
Operation oper=null;
switch(operation){
case '+' :
oper=new OperationAdd();
break;
case '-':
oper=new OperationSub();
break;
case '*':
oper=new OperationMul();
break;
case '/':
oper=new OperationDiv();
break;
default:
break;
}
return oper;
}

}

客户端类:

package yx.designpattern.simpleFactory;

public class Test {

public static void main(String[] args) {
Operation oper;
oper=OperationFactory.createOperation('/');
oper.number1=1;
oper.number2=0;
try {
System.out.println(oper.getResult());
} catch (Exception e) {
e.printStackTrace();
}
}

}