简单工厂模式

1.建一个模板类(抽象类)(封装,让业务逻辑与界面逻辑分开,降低耦合度,更易维护和扩展)

/**

* 运算类

*/

public abstract class Operation {

private double _numberA=0;[]

private double _numberB=0;

public abstract double GetResult() throws Exception;

public double get_numberA() {return _numberA;}

public void set_numberA(double _numberA) {this._numberA = _numberA;}

public double get_numberB() {return _numberB; }

public void set_numberB(double _numberB) {this._numberB = _numberB;}

}

2.将需要加工的类继承模板类(继承,让程序可以很灵活的修改和维护)

/**

* 加法类

*/

public class OperationAdd extends Operation {

@Override

public double GetResult() {

return get_numberA()+get_numberB();

}

}

/**

* 减法类

*/

public class OperationSub extends Operation {

@Override

public double GetResult() {

return get_numberA()-get_numberB();

}

}

/**

* 乘法类

*/

public class OperationMul extends Operation {

@Override

public double GetResult() {

return get_numberA()*get_numberB();

}

}

/**

* 除法类

*/

public class OperationDiv extends Operation {

@Override

public double GetResult() throws Exception {

double result=0;

if(get_numberB()==0) {

throw new Exception("除数不能为0");

}

result=get_numberA()/get_numberB();

return result;

}

}

 

3.创建工厂类,将要加工的类放到工厂类里面去加工(多态,让程序能更好的扩展)

/**

* 运算工厂类

*/

public class OperationFactory {

public static Operation createOperation(String operate)

{

Operation operation=null;

switch(operate){

case "+":

operation=new OperationAdd();

break;

case "-":

operation=new OperationSub();

break;

case "*":

operation=new OperationMul();

break;

case "/":

operation=new OperationDiv();

break;

}

return operation;

}

}

4.告诉工厂要加工的类,就能通过父类得到要加工的实例。

public class TestFactory {

public static void main(String[] args) throws Exception {

Operation operation=OperationFactory.createOperation("/");

operation.set_numberA(1);

operation.set_numberB(0);

System.out.println(operation.GetResult());

}

}

 

简单工厂模式:通过面向对象的三大特性封装、继承、多态让程序业务逻辑和界面逻辑耦合度低,程序更易维护和扩展。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值