里氏替换原则
在子类继承父类时,类中的方法需要保证与父类的行为预期一致
好的继承:
<?php
abstract class Animal
{
public function makeSound()
{
echo 'Make some sound';
}
}
class Cat extends Animal
{
public function makeSound()
{
echo 'Meow~ Meow~';
}
}
function makeAnimalSounds(Animal $animal)
{
$animal->makeSound();
}
makeAnimalSounds(new Cat());
在子类覆写父类的方法时,与其行为预期表现一致,不会导致程序产生意外的错误。
<?php
abstract class Animal
{
public function makeSound()
{
echo 'Make some sound';
}
}
class Dog extends Animal
{
public function makeSound()
{
throw new Exception("I can't make sound");
}
}
function makeAnimalSounds(Animal $animal)
{
$animal->makeSound();
}
makeAnimalSounds(new Dog());
子类的 makeSound()
方法返回值与父类不一致,容易产生意外的 Bug。
里氏替换原则最终的目的是「子类」可以完全替代「父类」,这就意味着子类的方法实现的功能要和父类一致。
换言之:子类的方法应该具有与父类相同的输入和输出,即使是 Bug,也要一模一样。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: