短篇故事:一个邮递员被要求挨家挨户地接收写有地址的信封(信件、文件、支票、礼品卡、申请书、情书)。
假设没有封面,让邮递员挨家挨户地接收所有的东西,然后交给其他人,邮递员会感到困惑。
所以最好用封面(在我们的故事中是接口)包装它,然后他就会很好地完成他的工作。
现在邮差的工作只是收和送封皮(他不关心封皮里面有什么)。
创建一个接口类型,而不是实际类型,而是使用实际类型实现它。
创建一个接口意味着你的组件可以很容易地适应其余的代码
我给你们举个例子。
你有一个plane界面,如下所示。
interface Airplane{
parkPlane();
servicePlane();
}
假设在平面的Controller类中有这样的方法
parkPlane(Airplane plane)
and
servicePlane(Airplane plane)
在您的程序中实现。它不会破坏你的代码。
我的意思是,只要它接受参数plane,它就不需要改变。
因为它将接受任何飞机,不管实际类型,飞行员,高空飞行,战斗机等。
同样,在集合中:
列表> <飞机飞机;//会占用你所有的飞机。
下面的例子将帮助您理解。
你有一架战斗机来执行它,所以
public class Fighter implements Airplane {
public void parkPlane(){
// Specific implementations for fighter plane to park
}
public void servicePlane(){
// Specific implementatoins for fighter plane to service.
}
}
HighFlyer和其他类也是如此:
public class HighFlyer implements Airplane {
public void parkPlane(){
// Specific implementations for HighFlyer plane to park
}
public void servicePlane(){
// specific implementatoins for HighFlyer plane to service.
}
}
现在假设你的控制器类多次使用AirPlane,
假设你的控制器类是ControlPlane,如下所示,
public Class ControlPlane{
AirPlane plane;
// so much method with AirPlane reference are used here...
}
神奇的是,你可以在不改变ControlPlane类代码的情况下,尽可能多地创建新的AirPlane类型实例。
你可以添加一个实例…
JumboJetPlane // implementing AirPlane interface.
AirBus // implementing AirPlane interface.
您也可以删除以前创建的类型的实例。