接口的实际应用-->制定标准
范例:制定USB标准
interface USB{ //定义USB接口 public void start(); //USB设备开始工作 public void stop(); //USB设备停止工作 } class Computer{ public static void plugin(USB usb){ //只要是USB设备就都可以插入 usb.start(); //让USB设备开始工作 System.out.println("========USB设备工作========"); usb.stop(); //让USB设备停止工作 } } class Flash implements USB{ //U盘 public void start(){ //覆写start()方法 System.out.println("U盘开始工作"); } public void stop(){ //覆写stop()方法 System.out.println("U盘停止工作"); } } class Print implements USB{ //打印机 public void start(){ //覆写start()方法 System.out.println("打印机开始工作"); } public void stop(){ //覆写stop()方法 System.out.println("打印机停止工作"); } } public class InterfaceCaseDemo02{ public static void main(String args[]){ Computer.plugin(new Flash()); //插入U盘 Computer.plugin(new Print()); //插入打印机 } } |
设计模式-->工厂设计
范例:观察程序中的问题
interface Fruit{ //定义Fruit接口 public void eat(); //吃水果的方法 } class Apple implements Fruit{ //子类Apple实现父类接口 public void eat(){ //覆写eat()方法 System.out.println("** 吃苹果"); } } class Orange implements Fruit{ //定义子类Orange public void eat(){ //覆写eat()方法 System.out.println("** 吃橘子"); } } public class InterfaceCaseDemo03{ public static void main(String args[]){ Fruit fru1 = new Apple(); //实例化接口 Fruit fru2 = new Orange(); //实例化接口 fru1.eat(); //调用方法 fru2.eat(); //调用方法 } }
//此方法不太合理 |
看下边à工厂设计模式
interface Fruit{ //定义Fruit接口 public void eat(); //吃水果的方法 } class Apple implements Fruit{ //子类Apple实现父类接口 public void eat(){ //覆写eat()方法 System.out.println("** 吃苹果"); } } class Orange implements Fruit{ //定义子类Orange public void eat(){ //覆写eat()方法 System.out.println("** 吃橘子"); } } class Factory{ //定义工厂 public static Fruit getInstance(String className){ Fruit f = null; //定义接口对象 if("apple".equals(className)){ //判断是哪个子类的标记 f = new Apple(); //通过Apple类实例化接口 } if("orange".equals(className)){ //判断是哪个子类的标记 f = new Orange(); //通过Orange类实例化接口 } return f; } } public class InterfaceCaseDemo04{ public static void main(String args[]){ Fruit f = null; //定义接口对象 f = Factory.getInstance(args[0]); //通过工厂取得实例 f.eat(); //调用方法 } } |