001-设计模式之简单工厂模式
1 /** 2 * 名称: 简单工厂模式 3 * 详情: 4 * 1.UML图中 '+':public '-':private '#':protected 5 * 2.UML图中 继承--(空心三角形+实线) 6 * 接口--(空心三角形+虚线) 7 * 关联--[当一个类'知道'另一个类,有相互调用,箭头指向另一个类]--(箭头+实线) 8 * 聚合--[弱拥有,大雁和雁群的关系,箭头指向部分]--(空心菱形+实线+箭头) 9 * 合成/组合--[强拥有,鸟和翅膀的关系,箭头指向部分]--(实心菱形+实线+箭头) 10 * 依赖--[动物依赖于氧气和水,区分于聚合和组合,箭头指向被依赖类]--(虚线+箭头) 11 * 12 * 3.简单工厂模式指的是使用一个简单的类来进行实例的创建 例如:计算器的实现 13 * 14 */ 15 16 /** 17 * 操作类 18 */ 19 abstract class Operation{ 20 private double NumA = 0; 21 private double NumB = 0; 22 23 public double getNumA() { 24 return NumA; 25 } 26 27 public double getNumB() { 28 return NumB; 29 } 30 31 public void setNumA(double numA) { 32 NumA = numA; 33 } 34 35 public void setNumB(double numB) { 36 NumB = numB; 37 } 38 39 abstract public double GetResult(); 40 } 41 42 /** 43 * 加法 44 */ 45 class OperationAdd extends Operation{ 46 47 @Override 48 public double GetResult() { 49 double result = 0; 50 result = getNumA() + getNumB(); 51 return result; 52 } 53 } 54 55 /** 56 * 减法 57 */ 58 class OperationSub extends Operation{ 59 60 @Override 61 public double GetResult() { 62 double result = 0; 63 result = getNumA() - getNumB(); 64 return result; 65 } 66 } 67 68 /** 69 * 乘法 70 */ 71 class OperationMul extends Operation{ 72 73 @Override 74 public double GetResult() { 75 double result = 0; 76 result = getNumA() * getNumB(); 77 return result; 78 } 79 } 80 81 /** 82 * 乘法 83 */ 84 class OperationDiv extends Operation{ 85 86 @Override 87 public double GetResult() { 88 double result = 0; 89 result = getNumA() / getNumB(); 90 return result; 91 } 92 } 93 94 /** 95 * 简单工厂 96 */ 97 class OperationSimpleFactory{ 98 public static Operation createOperation(String operate){ 99 Operation oper = null; 100 switch (operate){ 101 case "+": 102 oper = new OperationAdd(); 103 break; 104 case "-": 105 oper = new OperationSub(); 106 break; 107 case "*": 108 oper = new OperationMul(); 109 break; 110 case "/": 111 oper = new OperationDiv(); 112 break; 113 } 114 return oper; 115 } 116 } 117 118 119 public class SimpleFactory01 { 120 121 public static void main(String[] args) { 122 123 /** 124 * 调用 125 */ 126 Operation add = OperationSimpleFactory.createOperation("+"); 127 add.setNumA(10); 128 add.setNumB(20); 129 double result = add.GetResult(); 130 } 131 }