标签:style blog class code c java
接口:打印机接口
interface Printer { public void read(); }
函数一:佳能打印机
class CanPrinter implements Printer { public void read(){ System.out.println("Canread"); }; }
函数二:惠普打印机
class HPPrinter implements Printer { public void read(){ System.out.println("HPread"); }; }
主函数:
class Test { public static void main(String args[]){ int flag=0; Printer p = null; if(flag==0){ p = new HPPrinter(); }else{ p = new CanPrinter(); } p.read(); } }
得出:HPread
二次整合
接口、函数一、二不变,增加判断flag的类,方便修改
class PrinterFactory { Printer getPrinter(int flag){ //定义类型为Printer Printer p = null; if(flag==0){ p = new HPPrinter(); }else if(flag==1){ p = new CanPrinter(); } return p; //返回对象 } }
主函数:
class Test { public static void main(String args[]){ int flag=0; PrinterFactory f = new PrinterFactory(); Printer printer = f.getPrinter(flag); printer.read(); } }
标签:style blog class code c java
原文地址:http://www.cnblogs.com/tinyphp/p/3732941.html