Java 中的多态和接口(可以使用多态来实现接口......为什么?) [英] Polymorphism and Interfaces in Java (can polymorphism be used to implement interfaces...why?)

查看:29
本文介绍了Java 中的多态和接口(可以使用多态来实现接口......为什么?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现实世界中,人们用它做什么(解决什么类型的问题)?我可以看到这些一起工作的一些示例代码吗?我只能找到关于猫和狗说话或人们喝牛奶或咖啡的代码......

In the real world what do people use this for (to solve what types of problems)? Can I see some example code of these working together? All I can find is code about cats and dogs speaking or people drinking milk or coffee...

人们真的用接口实现多态吗?干什么用的?

Do people really implement polymorphism with interfaces? What for?

推荐答案

好的,

以下是观察者"模式的具体示例,使用类和接口在记录器系统中完成多态行为:

Below is concrete example of the "Observer" pattern, using classes and interfaces to accomplish polymorphic behavior in a logger system:

interface ILogger{

   public void handleEvent (String event);
}

class FileLogger implements ILogger{

   public void handleEvent (String event){
       //write to file
   }
}

class ConsoleLogger implements ILogger{

   public void handleEvent (String event){
       System.out.println( event );
   }
}

class Log {

   public void registerLogger (ILogger logger){

       listeners.add(logger);
   }

   public void log (String event){

       foreach (ILogger logger in listeners){

            logger.handleEvent(event); //pass the log string to both ConsoleLogger and FileLogger!
       }
   }

   private ArrayList<ILogger> listeners;
}

然后,您可以按如下方式使用它:

Then, you could use it as follows:

public static void main(String [] args){

     Log myLog();
     FileLogger myFile();
     ConsoleLogger myConsole();

     myLog.registerLogger( myFile );    
     myLog.registerLogger( myConsole );

    myLog.log("Hello World!!");
    myLog.log("Second log event!");
}

希望这有助于您理解接口和多态性.

Hope this helps your understanding of interfaces and polymorphism.

这篇关于Java 中的多态和接口(可以使用多态来实现接口......为什么?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆