设计原则之里氏代换原则

设计原则之里氏代换原则

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.
}
}

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...