/**
* 总结来说就是先写一个抽象的父类
* 然后用具体的子类继承这个父类 重写父类中关键的抽象的方法
* 利用简单工厂类去生产出具体的子类,简单工厂里面的方法是静态方法,可以通过类名调用
* 在主函数中,用多态的方法,声明抽象父类的引用,去实例化简单工厂中的子类,然后这个对象就造好了,再进行操作即可。
*
*/
/**
* 抽象的运算符
*
* 以及它的四个子类
*
*/
public abstract class Operation {
private double _numberA = 0;
private double _numberB = 0;
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;
}
public abstract double GetResult();
}
class OperationAdd extends Operation{
@Override
public double GetResult(){
return get_numberA()+get_numberB();
}
}
class OperationSub extends Operation{
@Override
public double GetResult(){
return get_numberA()-get_numberB();
}
}
class OperationMul extends Operation{
@Override
public double GetResult(){
return get_numberA()*get_numberB();
}
}
class OperationDiv extends Operation{
@Override
public double GetResult(){
try {
return get_numberA()/get_numberB();
}
catch (NumberFormatException e)
{
System.out.println("除数不能为0!");
}
return get_numberA()/get_numberB();
}
}
/**
*
* 简单工厂模式,生产出操作符
*
* 用的是静态方法 这样就不用造对象了
*/
public class OperationFactory {
public static Operation createOperation(String operator)
{
Operation oper = null;
switch(operator)
{
case "+": oper = new OperationAdd(); break;
case "-": oper = new OperationSub(); break;
case "*": oper = new OperationMul(); break;
case "/": oper = new OperationDiv(); break;
}
return oper;
}
}
/**
* 对程序的终极追求:可维护、可复用、可拓展、灵活性好
* 编程有一原则:用尽可能的方法去避免重复
*
* 紧耦合 VS 松耦合
*/
public class ProgramTest {
public static void main(String[] args) {
Operation oper = OperationFactory.createOperation("+"); //体现了多态性,因为左边是Operation的引用,而右边是生产出了它的子类
oper.set_numberA(1);
oper.set_numberB(2);
System.out.println(oper.GetResult());
}
}