Open/Closed Principle (OCP)

Założenie: Zrozumieć i zaimplementować zasadę otwartego/zamkniętego (OCP) w PHP, tworząc elastyczny kod, który można rozszerzać bez modyfikowania istniejącego kodu.

Krok po kroku:

  1. Stworzenie interfejsu: Zdefiniujmy interfejs Shape, który będzie zawierał metodę obliczającą pole powierzchni.
  2. 
    interface Shape {
      public function getArea(): float;
    }
    				

    Ten kod definiuje interfejs Shape z metodą getArea(), która zwraca pole powierzchni figury.

  3. Implementacja konkretnych klas: Stwórzmy klasy Circle i Rectangle implementujące interfejs Shape.
  4. 
    class Circle implements Shape {
      private float $radius;
    
      public function __construct(float $radius) {
        $this->radius = $radius;
      }
    
      public function getArea(): float {
        return pi() * $this->radius * $this->radius;
      }
    }
    
    class Rectangle implements Shape {
      private float $width;
      private float $height;
    
      public function __construct(float $width, float $height) {
        $this->width = $width;
        $this->height = $height;
      }
    
      public function getArea(): float {
        return $this->width * $this->height;
      }
    }
    				

    Klasy Circle i Rectangle implementują metodę getArea(), obliczając pole powierzchni odpowiednio dla koła i prostokąta.

  5. Użycie klas: Użyjmy stworzonych klas do obliczenia pola powierzchni.
  6. 
    $circle = new Circle(5);
    $rectangle = new Rectangle(4, 6);
    
    echo "Pole koła: " . $circle->getArea() . "\n";
    echo "Pole prostokąta: " . $rectangle->getArea() . "\n";
    				

    Ten kod tworzy obiekty Circle i Rectangle i używa metody getArea() do obliczenia ich pól powierzchni.

  7. Dodanie nowej figury (rozszerzenie): Możemy dodać nową figurę, np. trójkąt, bez modyfikowania istniejącego kodu.
  8. 
    class Triangle implements Shape {
        private float $base;
        private float $height;
    
        public function __construct(float $base, float $height) {
            $this->base = $base;
            $this->height = $height;
        }
    
        public function getArea(): float {
            return 0.5 * $this->base * $this->height;
        }
    }
    				

    Dodanie klasy Triangle demonstruje łatwość rozszerzania kodu bez konieczności modyfikacji istniejących klas.

Ten przykład pokazuje podstawowe zastosowanie zasady OCP. Zachęcamy do dalszego zgłębiania tematu programowania obiektowego w PHP!

Dodaj komentarz 0

Your email address will not be published. Required fields are marked *