面向接口编程思想
package com.test;
/*面向接口編程:多態的好處:把實現類對象賦給接口類型變量,屏蔽了不同實現類之間的差異,從而可以做到通用編程 案例:使用USB設備來工作。*/
//指定USB規范
interface IUSB{void swapData();
}
class Mouse implements IUSB{public void swapData(){System.out.println("鼠標在移動");}
}
//USB版本打印機
class Print implements IUSB{public void swapData(){System.out.println("打印,嘟嘟嘟....");}
}
//主板
class MotherBoard {//把設備插入到主板中的功能,接受IUSB類型的對象public static void pluginIn(IUSB m){m.swapData();}
}
public class InterfacePratice {public static void main(String[] args){//鼠標Mouse m=new Mouse();MotherBoard.pluginIn(m);//類中的靜態方法可以直接:類名.方法名//安裝打印機Print p=new Print();MotherBoard.pluginIn(p);}
}
改進:
package com.test; /*面向接口編程:多態的好處:把實現類對象賦給接口類型變量,屏蔽了不同實現類之間的差異,從而可以做到通用編程 案例:使用USB設備來工作。*/ //指定USB規范 interface IUSB{void swapData(); } class Mouse implements IUSB{public void swapData(){System.out.println("鼠標在移動");} } //USB版本打印機 class Print implements IUSB{public void swapData(){System.out.println("打印,嘟嘟嘟....");} } //主板 class MotherBoard {private static IUSB[] usbs=new IUSB[6];private static int index=0;//把設備插入到主板中的功能,接受IUSB類型的對象public static void pluginIn(IUSB usb){if(index == usbs.length){System.out.println("usb插滿!");return;}usbs[index++]=usb;}//取出主板中的每一個USB設備,并工作public static void doWork(){for(IUSB usb:usbs){if(usb != null){usb.swapData();}}} } public class InterfacePratice {public static void main(String[] args){//鼠標Mouse m=new Mouse();MotherBoard.pluginIn(m);//類中的靜態方法可以直接:類名.方法名//安裝打印機Print p=new Print();MotherBoard.pluginIn(p);//調用主板的工作行為MotherBoard.doWork();} }總結
- 上一篇: MyBatis之使用resultMap实
- 下一篇: 主程成长之路