1.printer接口
//接口 ,每个打印机都有的的基本步骤 interface Printer { public void open(); public void close(); public void print(String s); }
2.惠普类,实现接口
//惠普打印机实现接口,并实现接口所有方法 class HHPrinter implements Printer{ public void open(){ System.out.print("HP open"); } public void print(String s){ System.out.print("HP print——>"+s); } public void close(){ System.out.print("HP close"); } }
3.佳能类,实现接口
//佳能打印机实现打印机接口,并实现接口中所有的方法 class ConnonPrenter implements Printer { private void clean(){ System.out.println("clean"); } public void open(){ System.out.println("cannon open"); } public void print(String s){ System.out.println("cannon print--->"+s); } public void close(){ System.out.println("cannon close"); } }
4.主函数
//主函数 class Test { public static void main(String args[]){ Printer printer = null; int flag = 0; if (flag==0) { printer=new HPPrinter(); } else if(flag==1){ printer= new CannonPrinter(); } printer.open(); printet.print("test"); printer.close(); } }
将多次用到的代码,封装:
//主函数 class Test { public static void main(String args[]){ Printer printer = null; int flag = 0; /*将此代码封装在PrinterFactory.java中。 if (flag==0) { printer=new HPPrinter(); } else if(flag==1){ printer= new CanonPrinter(); }*/ //调用此些代码 Printer p = PrinterFactory.getPrinter(flag); printer.open(); printet.print("test"); printer.close(); } }
PrinterFactory.java
class PrinterFactory { public static Printer getPrinter(int flag){ Printer printer = null; if (flag==0) { printer=new HPPrinter(); } else if(flag==1){ printer= new CanonPrinter(); } return printer; } }
此后如果要添加打印机,只需要在PrinterFactory.java中增加打印机选项,在主函数中调用即可。