简单工厂模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单工厂模式相关的知识,希望对你有一定的参考价值。
public class Main { public static void main(String[] args) { Factory factory = new Factory(); Operation operation = factory.createOperate("+"); operation.setNumberA(10); operation.setNumberB(5); System.out.println(operation.getResult()); } }
public class Factory{ public Operation createOperate(String operate){ switch (operate){ case "+": return new Add(); case "-": return new Sub(); } return null; } }
public abstract class Operation { 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; } private double numberA = 0; private double numberB = 0; public abstract double getResult(); } class Add extends Operation { @Override public double getResult() { return getNumberA() + getNumberB(); } } class Sub extends Operation { @Override public double getResult() { return getNumberA() - getNumberB(); } }
根据传入参数由工厂决定创建哪一个实例
以上是关于简单工厂模式的主要内容,如果未能解决你的问题,请参考以下文章