面向对象编程永远在考虑:解藕和复用。
设计模式是前辈总结的结果,这些模式都是基于问题本身的抽象,活学活用才是王道。
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
简单工厂模式具有面向对象编程的基本优点:封装、继承和多态。
/** * Created by hero on 16-3-29. */ 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(); }
/** * Created by hero on 16-3-29. */ public class OperationAdd extends Operation { @Override public double getResult() { return getNumberA() + getNumberB(); } }
/** * Created by hero on 16-3-29. */ public class OperationSub extends Operation { @Override public double getResult() { return getNumberA() - getNumberB(); } }
/** * Created by hero on 16-3-29. */ public class OperationFactory { public static Operation getOperatioin(String op) { Operation operation = null; switch (op) { case "+": operation = new OperationAdd(); break; case "-": operation = new OperationSub(); break; } return operation; } }
public class Main { public static void main(String[] args) { Operation operation = OperationFactory.getOperatioin("+"); operation.setNumberA(1); operation.setNumberB(2); System.out.println(operation.getResult()); } }