Java 中的多态和接口(可以使用多态来实现接口......为什么?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5423125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Polymorphism and Interfaces in Java (can polymorphism be used to implement interfaces...why?)
提问by ???
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?
人们真的用接口实现多态吗?做什么的?
回答by J T
Sure,
当然,
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.
希望这有助于您理解接口和多态性。
回答by corsiKa
Map<String,Person> peopleByName = new HashMap<String,Person>();
If, down the road, I decide the memory overhead of HashMap is too much, I can re-do this as a TreeMap, and live with the slightly more expensive lookup times
如果以后我认为 HashMap 的内存开销太大,我可以将其作为 TreeMap 重新执行,并忍受稍微昂贵的查找时间
Map<String,Person> peopleByName = new TreeMap<String,Person>();
Because peopleByName is a Map, not a TreeMap or a HashMap, all my calls are guaranteed to work on either map regardless of implementation.
因为 peopleByName 是 Map,而不是 TreeMap 或 HashMap,所以无论实现如何,我的所有调用都可以保证在任一映射上工作。
This is best illustrated with the following example
下面的例子可以很好地说明这一点
public class CatsAndDogsDrinkingMilkAndCoffee {
// what, no? :-(
}
回答by iluxa
interface Request {
Response execute();
}
interface Response {
String serialize();
}
class RequestProcessor {
void processRequest(Request r) {
logger.log("Request: " + r);
Response s = r.execute();
logger.log("Response: " + s);
connectionManager.write(r.serialize());
}
}
Say in this example, RequestProcesor doesn't need to know about implementations of Request and Response
在这个例子中说,RequestProcesor 不需要知道 Request 和 Response 的实现
回答by Peter Lawrey
Have a look at the code for Map/AbstractMap/HashMap as an example. You will find thousands of other examples in the JDK source which comes with the JDK (in src.zip)
以 Map/AbstractMap/HashMap 的代码为例。您将在 JDK 附带的 JDK 源代码中找到数以千计的其他示例(在 src.zip 中)
回答by avgvstvs
Another suggestion I'd have for "the real world" is in using spring batch. If you have a commonly used report format that follows a pattern like "pull data, create report, send to recipients" you can create an interface for your reports that enforces this standard. In this sense it works like a "template" that all batch reports would follow.
我对“现实世界”的另一个建议是使用弹簧批次。如果您有一种常用的报告格式遵循“提取数据、创建报告、发送给收件人”等模式,您可以为您的报告创建一个界面来强制执行此标准。从这个意义上说,它就像一个“模板”,所有批处理报告都将遵循它。
A boring example, but it's something I faced in my first year...
一个无聊的例子,但这是我第一年面临的事情......
回答by Dhruv Gairola
imagine "somebody" designed a huge program, with lotsa code. suppose that "that somebody" used interfaces in the design of some controller logic. now you are hired to work with this code which youve never seen before. you are asked to design a new controller class. all you need to do now is to implement the interface and make all its methods work.
想象一下“某人”设计了一个巨大的程序,其中包含大量代码。假设“那个人”在某些控制器逻辑的设计中使用了接口。现在你被雇来使用你以前从未见过的代码。你被要求设计一个新的控制器类。您现在需要做的就是实现接口并使其所有方法工作。
if that somebody had not used interfaces, then not only would you have to redesign the controller, but you would probably need to redesign potentially the whole project because there is very strong coupling between the controller class and the rest of the classes. this will take you months just to understand the code, not to mention the new set of bugs you would probably introduce..
如果有人没有使用接口,那么您不仅需要重新设计控制器,而且您可能需要重新设计整个项目,因为控制器类和其余类之间存在很强的耦合。这将花费您几个月的时间来理解代码,更不用说您可能会引入的新错误集了..
回答by MByD
Almost any Java application with GUI uses it (but of course not only GUI...). For example, look at the source of android VideoView(this is the first comes to my mind...)
几乎所有带有 GUI 的 Java 应用程序都使用它(当然不仅仅是 GUI...)。比如看android VideoView的源码(这是我第一个想到的……)
回答by Dhananjay
Have you wondered how LINQ in .net works ? It's all about Interfaces and polymorphism.
您是否想知道 .net 中的 LINQ 是如何工作的?这都是关于接口和多态性的。
You need to work on projects then you will come to know about all this.
你需要在项目上工作,然后你就会知道这一切。