项目结构:
运行结果:
=================================================
代码部分:
=================================================
/Factory/src/com/b510/test/FactoryTest.java
1 /** 2 * 3 */ 4 package com.b510.test; 5 6 import com.b510.factory.AddFactory; 7 import com.b510.ifactory.IFactory; 8 import com.b510.operate.Operation; 9 10 /** 11 * @author hongten(hongtenzone@foxmail.com) 12 * @date 2013-2-17 13 */ 14 public class FactoryTest { 15 16 public static void main(String[] args) { 17 IFactory operateFactory = new AddFactory();//这里如果我们想要换另外一种操作,那么只需要修改这里就可以啦,当然必须保证有这样的操作类供选择 18 Operation operation = operateFactory.createOperation(); 19 operation.setNumberA(20); 20 operation.setNumberB(34); 21 double result = operation.getResult(); 22 System.out.println(result); 23 } 24 }
/Factory/src/com/b510/ifactory/IFactory.java
1 /** 2 * 3 */ 4 package com.b510.ifactory; 5 6 import com.b510.operate.Operation; 7 8 /** 9 * 抽象工厂(所有的*Factory都实习抽象工厂) 10 * @author hongten(hongtenzone@foxmail.com) 11 * @date 2013-2-17 12 */ 13 public interface IFactory { 14 15 public Operation createOperation(); 16 }
/Factory/src/com/b510/factory/AddFactory.java
1 /** 2 * 3 */ 4 package com.b510.factory; 5 6 import com.b510.ifactory.IFactory; 7 import com.b510.operate.AddOperation; 8 import com.b510.operate.Operation; 9 10 /** 11 * @author hongten(hongtenzone@foxmail.com) 12 * @date 2013-2-17 13 */ 14 public class AddFactory implements IFactory{ 15 16 @Override 17 public Operation createOperation() { 18 return new AddOperation(); 19 } 20 21 }
/Factory/src/com/b510/operate/Operation.java
1 /** 2 * 3 */ 4 package com.b510.operate; 5 6 /** 7 * 操作类(所有的*Operation都继承操作类) 8 * @author hongten(hongtenzone@foxmail.com) 9 * @date 2013-2-17 10 */ 11 public class Operation { 12 13 private double numberA; 14 15 private double numberB; 16 17 public double getResult() { 18 double result = 0; 19 return result; 20 } 21 22 public double getNumberA() { 23 return numberA; 24 } 25 26 public void setNumberA(double numberA) { 27 this.numberA = numberA; 28 } 29 30 public double getNumberB() { 31 return numberB; 32 } 33 34 public void setNumberB(double numberB) { 35 this.numberB = numberB; 36 } 37 38 }
/Factory/src/com/b510/operate/AddOperation.java
1 /** 2 * 3 */ 4 package com.b510.operate; 5 6 /** 7 * 加法 8 * @author hongten(hongtenzone@foxmail.com) 9 * @date 2013-2-17 10 */ 11 public class AddOperation extends Operation{ 12 13 public double getResult(){ 14 double result = 0; 15 result = getNumberA() + getNumberB(); 16 return result; 17 } 18 }