通过工厂来返回不同的对象,可使用同一种方法。
抽象类:
public abstract class Operation { private double numA; private double numB; private double result; public double getNumA() { return numA; } public void setNumA(double numA) { this.numA = numA; } public double getNumB() { return numB; } public void setNumB(double numB) { this.numB = numB; } public abstract double getResult(); }
加减乘数实现类:
public class AddOperation extends Operation { public double getResult() { return super.getNumA()+super.getNumB(); } }public class SubOperation extends Operation { public double getResult() { return super.getNumA()-super.getNumB(); }}public class MulOperation extends Operation { public double getResult() { return super.getNumA()*super.getNumB(); }}public class DivOperation extends Operation { @Override public double getResult() { return super.getNumA()/super.getNumB(); }}
工厂类与实现:
public class OperationFactory { public static Operation createOperation(String type){ switch (type) { case "+": return new AddOperation(); case "-": return new SubOperation(); case "*": return new MulOperation(); case "/": return new DivOperation(); default: break; } return null; } public static void main(String[] args) { Operation operation; operation=OperationFactory.createOperation("+"); operation.setNumA(1); operation.setNumB(1); System.out.println(operation.getResult()); }}
这样通过控制显示层的代码即可控制整个实现逻辑。。。