工厂模式结构图
实例
1、创建抽象对象类Operation.java,具体对象类OperateAdd,java,OperateDivide.java,OperateMultiply.java,OperateSubtrct.java,抽象工厂类IFactory.java,具体实现工厂OperateAddFactory,java,OperateDivideFactory.java,OperateMultiplyFactory.java,OperateSubtrctFactory.java,视图类Main.java
2、具体实现(由于差异不大,过于简单,只描述部分源码):
Operation.java
public class Operation { public int numberA,numberB; public float result; public float getResult(){ return result; } }OperateAdd,java
public class OperateAdd extends Operation{ @Override public float getResult() { // TODO Auto-generated method stub return numberA + numberB; } }
IFactory.java
public interface IFactory { Operation createOperation(); }OperateAdd Factory ,java
public class OperateAddFactory implements IFactory{ @Override public Operation createOperation() { // TODO Auto-generated method stub return new OperateAdd(); } }Main.java
public class Main { public static void main(String[] args){ IFactory iFactory = new OperateAddFactory(); Operation operation = iFactory.createOperation(); operation.numberA = 11; operation.numberB = 22; System.out.println(operation.getResult()); } }