设计原则之里氏代换原则
发布时间:2020-12-14 02:01:31 所属栏目:百科 来源:网络整理
导读:设计原则之里氏代换原则substitute=replace替换sub下st石头i我tu土te特别我用石头替换下土,造了特比坚固的房子hierarchy['har??k]=level等级hi海豹er儿子arare是ch成龙海豹儿子的雷霆战机等级是比成龙高derive[di'raiv]起源,派生de德国riveriver河德国的莱
设计原则之里氏代换原则 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. } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |