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方法。好处在于:在一个大系统中生成对象使用打印机的功能时减少重复代码,使用者并不需要知道打印机的种类,同时也方便开发者修改打印机的种类
新闻热点
疑难解答