今天学习了简单工厂模式,总结一下。
简单工厂模式的核心思想是:由一个工厂实体决定创建出哪一种产品的实例。
比较简单,因此直接上代码:
这个例子我们实现一个简单的计算器。我们先定义一个计算行为接口,行为比较简单就是计算。
1 package com.java.simpleFactory;2 3 public interface CalcOperation {4 public float doCalc();5 }
接着我们分别用加减乘除不同的运算去实现这个接口。
1 package com.java.simpleFactory; 2 3 public class AddOperation extends DefaultOperation implements CalcOperation{ 4 5 public AddOperation(float a,float b){ 6 this.setA(a); 7 this.setB(b); 8 } 9 10 @Override11 public float doCalc() {12 return this.getA()+this.getB();13 }14 15 }16 17 18 package com.java.simpleFactory;19 20 public class MinusOperation extends DefaultOperation implements CalcOperation {21 22 public MinusOperation(float a,float b) {23 this.setA(a);24 this.setB(b);25 }26 27 28 @Override29 public float doCalc() {30 return this.getA()-this.getB();31 }32 33 }34 35 package com.java.simpleFactory;36 37 public class MultOperation extends DefaultOperation implements CalcOperation {38 39 public MultOperation(float a,float b) {40 this.setA(a);41 this.setB(b);42 }43 44 @Override45 public float doCalc() {46 return this.getA()*this.getB();47 }48 49 }50 51 package com.java.simpleFactory;52 53 public class DvdOperation extends DefaultOperation implements CalcOperation {54 55 public DvdOperation(float a,float b) {56 this.setA(a);57 this.setB(b);58 }59 60 @Override61 public float doCalc() {62 if(this.getB()==0)63 return 0;64 return this.getA()/this.getB();65 }66 67 }
最后就是我们的工厂类了
1 package com.java.simpleFactory; 2 3 public class OperationFactory { 4 5 public CalcOperation CreateOpreation(String sign,float a,float b){ 6 CalcOperation calcOperation = null; 7 switch(sign){ 8 case "+": 9 calcOperation = new AddOperation(a, b);10 break;11 case "-":12 calcOperation = new MinusOperation(a, b);13 break;14 case "*":15 calcOperation = new MultOperation(a, b);16 break;17 case "/":18 calcOperation = new DvdOperation(a, b);19 break;20 }21 return calcOperation;22 }23 24 }
测试一下
1 package com.java.simpleFactory; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 OperationFactory factory=new OperationFactory(); 7 CalcOperation operation = factory.CreateOpreation("/", 2, 3); 8 System.out.println(operation.doCalc()); 9 10 }11 12 }
简单工厂模式看着很简单,但是作用很大。推荐大佬的一片文章:http://www.cnblogs.com/zuoxiaolong/p/pattern4.html