微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

设计原则之里氏代换原则

设计原则之里氏代换原则

substitute=replace替换
sub下st石头i我tu土te特别
我用石头替换下土,造了特比坚固的房子

hierarchy['har��k]=level等级
hi海豹er儿子arare是ch成龙
海豹儿子的雷霆战机等级是比成龙高

derive[di'raiv]起源,派生
de德国riveriver河
德国的莱茵河起源于阿尔卑斯山

动机:
当我们创建类的层级(继承),我们继承一些类,创建一些派生类。我们必须确保新的派生类只是继承而不是代替父类方法。否则子类可能产生意想不到的影响当它们被使用的时候。

结论:里氏替换原则是开闭原则的扩展,它意味着我们要确保子类继承父类的时候不要改变父类的行为。

Example:当正方形类继承矩形类,setWidth()和setHeight()会产生误解

//ViolationofLikov'sSubstitutionPrinciple
classRectangle
{
protectedintm_width;
protectedintm_height;
publicvoidsetWidth(intwidth){
m_width=width;
}
publicvoidsetHeight(intheight){
m_height=height;
}
publicintgetWidth(){
returnm_width;
}
publicintgetHeight(){
returnm_height;
}
publicintgetArea(){
returnm_width*m_height;
}
}
classSquareextendsRectangle
{
publicvoidsetWidth(intwidth){
m_width=width;
m_height=width;
}
publicvoidsetHeight(intheight){
m_width=height;
m_height=height;
}
}
classLspTest
{
privatestaticRectanglegetNewRectangle()
{
//itcanbeanobjectreturnedbysomefactory...
returnnewSquare();
}
publicstaticvoidmain(Stringargs[])
{
Rectangler=LspTest.getNewRectangle();
r.setWidth(5);
r.setHeight(10);
//userkNowsthatrit'sarectangle.
//Itassumesthathe'sabletosetthewidthandheightasforthebaseclass
System.out.println(r.getArea());
//Nowhe'ssurprisedtoseethattheareais100insteadof50.
}
}

原文地址:https://www.jb51.cc/javaschema/283500.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐