Created
February 25, 2022 09:07
-
-
Save Nurzzzone/f789caf126a9ba2a03f883294abf34fd to your computer and use it in GitHub Desktop.
PHP solid принцип подстановки Барбары Лисков Liskov substitution principle, LSP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // index.php | |
| <?php | |
| /** | |
| * Solid | |
| * L - принцип подстановки Барбары Лисков | |
| * Liskov substitution principle, LSP | |
| * Функции, которые используют базовый тип, должны | |
| * иметь возможность использовать подтипы базового типа не зная об этом. | |
| * | |
| * Поведение наследуемых классов не должно противоречить | |
| * поведению заданному базовым классам | |
| */ | |
| $bird = new Bird(); | |
| // $bird = new Duck(); | |
| // $bird = new Penguin(); | |
| $birdRun = new BirdRun($bird); | |
| $birdRun->run(); | |
| // bird.php | |
| <?php | |
| /** | |
| * Реально используемый в коде класс | |
| */ | |
| class Bird { | |
| public function fly() { | |
| $flySpeed = 10; | |
| return $flySpeed; | |
| } | |
| } | |
| /** | |
| * Дочерний класс от Bird | |
| * Не изменяет поведение, но дополняет | |
| * Не нарушает принцип LSP | |
| */ | |
| class Duck extends Bird { | |
| public function fly() { | |
| $flySpeed = 8; | |
| return $flySpeed; | |
| } | |
| public function swim() { | |
| $swimSpeed = 2; | |
| return $swimSpeed; | |
| } | |
| } | |
| /** | |
| * Дочерний класс от Bird | |
| * Изменяет поведение | |
| * Нарушает принцип LSP | |
| */ | |
| class Penguin extends Bird { | |
| public function fly() { | |
| return 'I can\'t fly!'; // не типичное поведение | |
| } | |
| // возможное решение для соблюдение принципа LSP | |
| // public function fly() { | |
| // $flySpeed = 0; | |
| // return $flySpeed; | |
| // } | |
| public function swim() { | |
| $swimSpeed = 6; | |
| return $swimSpeed; | |
| } | |
| } | |
| // birdRun.php | |
| <?php | |
| class BirdRun { | |
| private $bird; | |
| public function __construct(Bird $bird) { | |
| $this->bird = $bird; | |
| } | |
| public function run() { | |
| $flySpeed = $this->bird->fly(); | |
| // ... | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment