- 向上转型。去if、else,面向业务内容,优雅的将平面逻辑立体化。
1 package upperConvert; 2 3 public class UpperConvert { 4 5 /** 6 * 向上转型 7 */ 8 public static void main(String[] args) { 9 UpperConvert.run(new LCDMonitor()); 10 UpperConvert.run(new CRTMonitor()); 11 UpperConvert.run(new PlasmaMonitor()); 12 } 13 14 public static void run(Monitor monitor) { 15 monitor.displayText(); 16 monitor.displayGraphics(); 17 } 18 19 } 20 21 class Monitor { 22 public void displayText() { 23 } 24 25 public void displayGraphics() { 26 } 27 } 28 29 class LCDMonitor extends Monitor { 30 public void displayText() { 31 System.out.println("LCD display text"); 32 } 33 34 public void displayGraphics() { 35 System.out.println("LCD display graphics"); 36 } 37 } 38 39 class CRTMonitor extends Monitor { 40 public void displayText() { 41 System.out.println("CRT display text"); 42 } 43 44 public void displayGraphics() { 45 System.out.println("CRT display graphics"); 46 } 47 } 48 49 class PlasmaMonitor extends Monitor { 50 public void displayText() { 51 System.out.println("Plasma display text"); 52 } 53 54 public void displayGraphics() { 55 System.out.println("Plasma display graphics"); 56 } 57 }
源码地址:http://files.cnblogs.com/files/xiluhua/UpperConvert.rar