interface PRinter{public void open();public void close();public void print(String s);}
class HP implements Printer{public void open(){System.out.println("惠普打印機開機");}public void print(String s){System.out.println(s);}private void clean(){System.out.println("清洗");}public void close(){this.clean();System.out.println("惠普打印機關機");}}class Canon implements Printer{public void open(){System.out.println("佳能打印機開機");}public void print(String s){System.out.println(s);}public void close(){System.out.println("佳能打印機關機");}}class PrintFactory{public static Printer getPrinter(int flag){//根據用戶所選擇的打印機生成相應的打印機對象并向上轉型為Printer類型Printer printer = null;if(flag == 1){printer = new HP();}else{printer = new Canon();}return printer;}} class test{public static void main(String args[]){int flag = 0;Printer p = PrintFactory.getPrinter(flag);p.open();p.print("test");p.close();}}
Printer是接口,HP類和Canon類用來實現接口,生成HP和Canon兩個類的對象的代碼封裝在PrintFactory的getPrinter方法中。當需要生成打印機對象時,調用PrintFactory的getPrinter方法。好處在于:在一個大系統中生成對象使用打印機的功能時減少重復代碼,使用者并不需要知道打印機的種類,同時也方便開發者修改打印機的種類
新聞熱點
疑難解答