简单工厂模式
Posted 仙人掌的刺
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单工厂模式相关的知识,希望对你有一定的参考价值。
面向对象编程永远在考虑:解藕和复用。
设计模式是前辈总结的结果,这些模式都是基于问题本身的抽象,活学活用才是王道。
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
简单工厂模式具有面向对象编程的基本优点:封装、继承和多态。
/** * 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()); } }
以上是关于简单工厂模式的主要内容,如果未能解决你的问题,请参考以下文章