1 package refactoring; 2 3 /** 4 * @title Object oriented polymorphism 5 * @description 面向对象多态取代switch 6 * @author LZH 7 * @date 2016-8-2 下午10:48:51 8 */ 9 public class OOPReplaceSwitch { 10 11 public static void main(String[] args) { 12 13 int employeeType = 3; 14 15 double salary = EmployeeFactory.getInstance(employeeType) 16 .getMonthSalary(); 17 18 System.out.println(String.format("薪资:%s 元", salary)); 19 } 20 } 21 22 /** 23 * @title EmployeeType 24 * @description 员工类型 25 * @author LZH 26 * @date 2016-8-2 下午10:28:33 27 */ 28 enum EmployeeType { 29 30 /** 工程师 */ 31 ENGINNER(1), 32 33 /** 销售员 */ 34 SALESMAN(2), 35 36 /** 经理 */ 37 MANAGER(3); 38 39 private int type; 40 41 private EmployeeType(int type) { 42 this.type = type; 43 } 44 45 public int getType() { 46 return type; 47 } 48 } 49 50 /** 51 * @title EmployeeFactory 52 * @description 员工工厂类 53 * @author LZH 54 * @date 2016-8-2 下午10:20:45 55 */ 56 class EmployeeFactory { 57 58 /** 59 * 根据员工类型获取具体员工实例 60 * 61 * @param employeeType 62 * @return 63 */ 64 public static Employee getInstance(int employeeType) { 65 66 if (employeeType == EmployeeType.ENGINNER.getType()) { 67 return new Enginner(); 68 } 69 70 if (employeeType == EmployeeType.SALESMAN.getType()) { 71 return new Salesman(); 72 } 73 74 if (employeeType == EmployeeType.MANAGER.getType()) { 75 return new Manager(); 76 } 77 78 throw new RuntimeException("unkown type!"); 79 } 80 } 81 82 /** 83 * @title Employee 84 * @description 员工基类 85 * @author LZH 86 * @date 2016-8-2 下午10:19:13 87 */ 88 interface Employee { 89 90 /** 91 * 获取薪资 92 * 93 * @return 94 */ 95 public double getMonthSalary(); 96 } 97 98 /** 99 * @title Enginner 100 * @description 工程师 101 * @author LZH 102 * @date 2016-8-2 下午10:19:20 103 */ 104 class Enginner implements Employee { 105 106 @Override 107 public double getMonthSalary() { 108 return 10 * 1000; 109 } 110 111 } 112 113 /** 114 * @title Salesman 115 * @description 销售员 116 * @author LZH 117 * @date 2016-8-2 下午10:19:29 118 */ 119 class Salesman implements Employee { 120 121 @Override 122 public double getMonthSalary() { 123 return 20 * 1000; 124 } 125 126 } 127 128 /** 129 * @title Manager 130 * @description 经理 131 * @author LZH 132 * @date 2016-8-2 下午10:19:26 133 */ 134 class Manager implements Employee { 135 136 @Override 137 public double getMonthSalary() { 138 return 30 * 1000; 139 } 140 141 }
原文:http://www.cnblogs.com/llrex56/p/5731081.html