老生长谈的两个设计模式了,这里把这两个设计模式对比着来总结一下。
什么是简单工厂模式?
简单工厂模式:根据传入工厂类的参数动态决定要创建哪一个产品类的实例。
UML图如下(以实现一个计算器为例):
简单工厂模式的Java代码实现如下:
1 package designPattern; 2 /** 3 * 简单工厂模式 4 * @author yiRain 5 * 6 */ 7 public class SimpleFactory { 8 9 public static void main(String[] args){ 10 11 double numberA = 6,numberB = 2; 12 13 FactoryOperation factoryOperation = new FactoryOperation(); 14 Operation add = factoryOperation.CreateOperate(‘+‘); 15 double addResult = add.GetResult(numberA, numberB); 16 17 Operation sub = factoryOperation.CreateOperate(‘-‘); 18 double subResult = sub.GetResult(numberA, numberB); 19 20 System.out.println("addResult="+addResult+",subResult="+subResult); 21 } 22 } 23 24 /** 25 * 26 * 运算类 27 * 28 */ 29 abstract class Operation{ 30 public double numberA, numberB; 31 public abstract double GetResult(double numberA,double numberB); 32 } 33 34 /** 35 * 36 * 加法类 37 * 38 */ 39 class addOperation extends Operation{ 40 41 @Override 42 public double GetResult(double numberA, double numberB) { 43 // TODO Auto-generated method stub 44 return numberA+numberB; 45 } 46 47 } 48 49 /** 50 * 51 * 减法类 52 * 53 */ 54 class subOperation extends Operation{ 55 56 @Override 57 public double GetResult(double numberA, double numberB) { 58 // TODO Auto-generated method stub 59 return numberA-numberB; 60 } 61 62 } 63 64 /** 65 * 66 * 工厂类 67 * 68 */ 69 class FactoryOperation{ 70 public Operation CreateOperate(char type){ 71 switch (type) { 72 case ‘+‘: 73 Operation add = new addOperation(); 74 return add; 75 case ‘-‘: 76 Operation sub = new subOperation(); 77 return sub; 78 default: 79 return null; 80 } 81 } 82 }
原文地址:https://www.cnblogs.com/yiRain1992/p/8372474.html
时间: 2024-10-11 17:44:50