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.
相关文章