1.依据条件的不同,工厂类创建不同的实例。(有同一父类)
2.调用父类的方法。
3.因为不同的实例,所以会调用到子类的方法,得到不同的结果。 ---> 利用多态
举例:
父类:
public 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(); }
4个子类:
public class OperationAdd extends Operation { @Override public double getResult() { return getNumberA() + getNumberB(); } }
public class OperationDiv extends Operation { @Override public double getResult() { return getNumberA() / getNumberB(); } }
public class OperationMul extends Operation { @Override public double getResult() { return getNumberA() * getNumberB(); } }
public class OperationSub extends Operation { @Override public double getResult() { return getNumberA() - getNumberB(); } }
工厂类:
public class OperationFactory { public static Operation creatOperation(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; } }
使用:
public class jisuanqi { public static void main(String[] args) { Operation operation = OperationFactory.creatOperation("*"); operation.setNumberA(2); operation.setNumberB(1); System.out.println(operation.getResult()); } }
时间: 2024-10-12 10:24:32