加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

设计模式 之 里氏替换原则 C++

发布时间:2020-12-13 23:12:40 所属栏目:百科 来源:网络整理
导读:里氏替换原则。 是对类继承的约束。 定义: 1。If for each object o1 of type S there is an object o2 of type T such that for all programs P defined of T,the behavior of P is unchanged when o1 is subsituted for o2 then S is a type of T. (如果

里氏替换原则。 是对类继承的约束。

定义: 1。If for each object o1 of type S there is an object o2 of type T such that for all programs P defined of T,the behavior of P is unchanged when o1 is subsituted for o2 then S is a type of T. (如果对每一个类型为S的对象o1 , 都有类型为T的对象o2,使得以T定义的程序P在所有的对象o1都替换成o2时,程序P的行为没有发生变化,那么类型S是类型T的子类型。

2.Founctions that use pointers or references to base classes must be able to use objects of dirvers classes without knowing it .


注意:如果自雷不能完整的实现父类的方法,或者父类的某些方法在子类中已经发生“畸变”,则建议断开父子继承关系,采用依赖、关联的关系代替继承。


‘契约设计’ 制定前置条件和后置条件,前置条件就是你要执行就必须满足我的条件;后置条件就是我执行完了需要反馈,标准是什么。

子类中的前置条件必须与父类中被覆写的方法的前置条件相同或者更宽松。




注意// 省略构造函数和析构函数

基类 AbstractGun

class AbstractGun

{

virtual void shoot();

}

class MachineGun:publicAbstractGun

{

virtualvoid shoot();

}

void MachineGun::shoot()
{
printf("机枪 射击");

}

void Rifir::shoot()
{
printf("狙击 射击");
}

void HandGun::shoot()
{
printf("手枪 射击");
}

void ToyGun::shoot()
{
printf("玩具枪 射击");
}

void Solider::setGun(AbstractGun gun)

{

this.gun = gun;

}

void Solider::shoot()

{

gun->shoot();

}

void main()

{

Solider *solider = new Solider();

solider->setGun(new RIfir);

solider->killEmeny();

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读