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());
}
}
简单工厂模式:通过面向对象的三大特性封装、继承、多态让程序业务逻辑和界面逻辑耦合度低,程序更易维护和扩展。