UML類圖:
硚口網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián),硚口網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為硚口超過千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢,請找那個售后服務(wù)好的硚口做網(wǎng)站的公司定做!Java版代碼:
abstract 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 abstract double GetResult();
}
class OperationAdd extends Operation {
@Override
public double GetResult() {
// TODO Auto-generated method stub double result = 0;
result= getNumberA() + getNumberB();
return result;
}
}
class OperationSub extends Operation{
@Override
public double GetResult() {
// TODO Auto-generated method stub double result=0;
result=getNumberA()-getNumberB();
return result;
}
}
class OperationMul extends Operation{
@Override
public double GetResult() {
// TODO Auto-generated method stub double result=0;
result=getNumberA()*getNumberB();
return result;
}
}
class operationDiv extends Operation{
@Override
public double GetResult() {
// TODO Auto-generated method stub double result=0;
if(getNumberB()==0){
System.out.println("除數(shù)不能為零!");
}else{
result=getNumberA()/getNumberB();
}
return result;
}
}
class OperationFactory{
public static Operation createOperate(String operate){
Operation oper=null;
switch(operate){
case "+":
oper=new OperationAdd();
break;
case "-":
oper=new OperationSub();
break;
case "*":
oper=new OperationMul();
break;
case "/":
oper=new operationDiv();
break;
}
return oper;
}
}
public class SimpleFactory{
public static void main(String[] args){
Operation oper;
oper=OperationFactory.createOperate("+");
oper.setNumberA(1);
oper.setNumberB(2);
double result=oper.GetResult();
System.out.println(result);
}
}
總結(jié):
這里的工廠類OperationFactory不是與具體的運算類相關(guān)聯(lián),而是與抽象運算類相關(guān)聯(lián),這樣就降低了耦合度,即使要擴展或修改也不需要大范圍的修改代碼,
增強了代碼的可維護性和可擴展性。