在我的开发学习中,我觉得我必须学习更多关于接口的知识。
我经常读到它们,但我似乎无法理解它们。
我读过这样的例子:动物基类,IAnimal接口的东西,如“Walk”,“Run”,“GetLegs”等-但我从来没有工作过,觉得“嘿,我应该在这里使用接口!”
我错过了什么?为什么这个概念对我来说这么难理解!我只是害怕这样一个事实,我可能从来没有意识到一个具体的需要-主要是由于一些缺失的理解他们!这让我觉得我作为一名开发人员缺少了一些东西!如果有人有过这样的经历,并取得了突破,我会很感激一些关于如何理解这个概念的建议。谢谢你!
假设你想要模拟当你试图睡觉时可能发生的烦恼。
接口前的模型
class Mosquito {
void flyAroundYourHead(){}
}
class Neighbour{
void startScreaming(){}
}
class LampJustOutsideYourWindow(){
void shineJustThroughYourWindow() {}
}
正如你清楚地看到的,当你试图睡觉时,许多“事情”都可能令人讨厌。
使用没有接口的类
但是在使用这些类时,我们遇到了一个问题。他们毫无共同之处。您必须分别调用每个方法。
class TestAnnoyingThings{
void testAnnoyingThinks(Mosquito mosquito, Neighbour neighbour, LampJustOutsideYourWindow lamp){
if(mosquito != null){
mosquito.flyAroundYourHead();
}
if(neighbour!= null){
neighbour.startScreaming();
}
if(lamp!= null){
lamp.shineJustThroughYourWindow();
}
}
}
带有接口的模型
为了克服这个问题,我们可以引入一个iterface
interface Annoying{
public void annoy();
}
并在类中实现它
class Mosquito implements Annoying {
void flyAroundYourHead(){}
void annoy(){
flyAroundYourHead();
}
}
class Neighbour implements Annoying{
void startScreaming(){}
void annoy(){
startScreaming();
}
}
class LampJustOutsideYourWindow implements Annoying{
void shineJustThroughYourWindow() {}
void annoy(){
shineJustThroughYourWindow();
}
}
接口使用
这将使这些类的使用更容易
class TestAnnoyingThings{
void testAnnoyingThinks(Annoying annoying){
annoying.annoy();
}
}
我喜欢军队的比喻。
中士不在乎你是软件开发人员、音乐家还是律师。
你被当作士兵对待。
对于中士来说,不去操心与他一起工作的人的具体细节更容易,
把每个人都当作抽象的士兵(…如果他们表现得不像孩子,就要惩罚他们)。
人们像士兵一样行动的能力被称为多态性。
接口是帮助实现多态的软件结构。
为了实现简单,需要抽象细节,这就是你问题的答案。
Polymorphism, which etymologically means "many forms," is the ability to treat an object of any subclass of a base class as if it were an object of the base class. A base class has, therefore, many forms: the base class itself, and any of its subclasses.
(..) This makes your code easier for you to write and easier for others to understand. It also makes your code extensible, because other subclasses could be added later to the family of types, and objects of those new subclasses would also work with the existing code.
它解决了一个具体的问题:
你有a b c d四种不同类型。在你的代码中,你可以这样写:
a.Process();
b.Process();
c.Process();
d.Process();
为什么不让他们实现IProcessable呢
List<IProcessable> list;
foreach(IProcessable p in list)
p.Process();
当你添加50种类型的类,它们都做同样的事情时,这种伸缩性会更好。
另一个具体问题是:
你有没有看过System.Linq.Enumerable?它定义了大量的扩展方法,可以对实现IEnumerable的任何类型进行操作。因为任何实现IEnumerable的东西基本上都在说“我支持无序foreach类型模式中的迭代”,所以你可以为任何可枚举类型定义复杂的行为(Count、Max、Where、Select等)。