1 被客户不断变化的需求 “折磨”
第一次需求
class Printer{void Open(){System out printl
1.被客户不断变化的需求 “折磨”
第一次需求
class Printer{ void Open(){ System.out.println("Open"); } void Close(){ System.out.println("Close"); } void Print(String s){ System.out.println("Print--->" + s); } }
1 class Test{ 2 public static void main(String args []){ 3 Printer printer = new Printer(); 4 printer.Open(); 5 printer.Print("abc"); 6 printer.Close(); 7 } 8 }
第二次需求
1 class HPPrinter{ 2 void Open(){ 3 System.out.println("Open"); 4 } 5 6 void Close(){ 7 System.out.println("Close"); 8 } 9 10 void Print(String s){ 11 System.out.println("Print--->" + s); 12 } 13 }
1 class CannonPrinter{ 2 void Open(){ 3 System.out.println("Open"); 4 } 5 6 void Close(){ 7 this.Clean(); 8 System.out.println("Close"); 9 } 10 11 void Print(String s){ 12 System.out.println("Print--->" + s); 13 } 14 15 void Clean(){ 16 System.out.println("Clean"); 17 } 18 }
1 class Test{ 2 public static void main(String args []){ 3 int flag = 0; 4 5 if( flag == 0){ 6 HPPrinter hpprinter = new HPPrinter(); 7 hpprinter.Open(); 8 hpprinter.Print("abc"); 9 hpprinter.Close(); 10 } 11 else if( flag == 1){ 12 CannonPrinter cannonprinter = new CannonPrinter(); 13 cannonprinter.Open(); 14 cannonprinter.Print("abc"); 15 cannonprinter.Close(); 16 } 17 } 18 }
第二次需求优化(消除重复代码)
1 class Printer{ 2 void Open(){ 3 System.out.println("Open"); 4 } 5 6 void Close(){ 7 System.out.println("Close"); 8 } 9 10 void Print(String s){ 11 System.out.println("Print--->" + s); 12 } 13 }
1 class HPPrinter extends Printer{2 }
1 class CannonPrinter extends Printer{ 2 void Close(){ 3 this.Clean(); 4 super.Close(); 5 } 6 7 void Clean(){ 8 System.out.println("Clean"); 9 } 10 }
1 class Test{ 2 public static void main(String args []){ 3 int flag = 1; 4 5 if( flag == 0){ 6 HPPrinter hpprinter = new HPPrinter(); 7 hpprinter.Open(); 8 hpprinter.Print("abc"); 9 hpprinter.Close(); 10 } 11 else if( flag == 1){ 12 CannonPrinter cannonprinter = new CannonPrinter(); 13 cannonprinter.Open(); 14 cannonprinter.Print("123"); 15 cannonprinter.Close(); 16 } 17 } 18 }