设计模式学习笔记——简单工厂模式-创新互联

UML类图:

硚口网站建设公司成都创新互联,硚口网站设计制作,有大型网站制作公司丰富经验。已为硚口超过千家提供企业网站建设服务。企业网站搭建\成都外贸网站制作要多少钱,请找那个售后服务好的硚口做网站的公司定做!

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("除数不能为零!");
        }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);
    }
}

总结:

这里的工厂类OperationFactory不是与具体的运算类相关联,而是与抽象运算类相关联,这样就降低了耦合度,即使要扩展或修改也不需要大范围的修改代码,

增强了代码的可维护性和可扩展性。


分享标题:设计模式学习笔记——简单工厂模式-创新互联
URL地址:http://scyanting.com/article/dssgic.html