Polymorfisme ved hjælp af abstrakte klasser og grænseflader

I denne artikel lærer du, hvordan du deler og håndhæver kode med polymorfisme ved hjælp af abstrakte klasser og grænseflader.

Vi dykker dybere ned i objektorienteret programmering og forsøger at tænke i form af designmønstre for at dele og håndhæve vores kode ved hjælp af polymorfisme.

Abstrakt klasse

Lad os sige, at vi har en klasse kaldet Mand med nogle egenskaber ( name, age, height, fav_drinksog fav_sports) og metoder ( giveFirmHandshakes, beStubbornog notPutToiletPaper).

name = $name; $this->age = $age; $this->height = $height; } public function giveFirmHandshakes() { return "I give firm handshakes."; } public function beStubborn() { return "I am stubborn."; } public function notPutToiletPaper() { return "It's not humanly possible to remember to put toilet paper rolls when they are finished"; } }

Vi er nødt til at specificere navn, alder og højde for at starte denne klasse som krævet af konstruktøren.

name, $jack->age, $jack->height); // => Jack - 26 - 5 Feet 6 Inches

Lad os sige, at vi vil tilføje en ny metode til denne klasse kaldet isActive.

Denne metode kontrollerer, om ejendommen er aktiv, og returnerer den relevante meddelelse afhængigt af værdien af ​​aktiv, med standardværdien for falsk. Vi kan sætte det til sandt for de mænd, der er aktive.

active == true) { return "I am an active man."; } else { return "I am an idle man."; } } } $jack = new Man('Jack', '26', '5 Feet 6 Inches'); $jack->active = true; echo $jack->isActive(); // => I am an active man. $jake = new Man('Jake', '30', '6 Feet'); echo "\n" . $jake->isActive(); // => I am an idle man.

Hvad hvis en mand ikke bare er aktiv eller inaktiv?

Hvad hvis der er en skala fra 1 til 4, der måler, hvor aktiv en mand er (1 - inaktiv, 2 - let aktiv, 3 - moderat aktiv, 4 - meget aktiv)?

Vi kan have en if..elseif..else-erklæring som denne:

active == 1) { return "I am an idle man."; } elseif ($this->active == 2) { return "I am a lightly active man."; } elseif ($this->active == 3) { return "I am a moderately active man."; } else { return "I am a very active man."; } }

Lad os nu tage dette et skridt videre.

Hvad hvis menneskets aktive egenskab ikke kun er et heltal (1, 2, 3, 4 osv.)? Hvad hvis værdien af ​​aktiv er "atletisk" eller "doven"?

Behøver vi ikke tilføje flere andet, hvis udsagn på udkig efter et match med disse strenge?

Abstrakte klasser kan bruges til et sådant scenario.

Med abstrakte klasser definerer du grundlæggende klassen som abstrakt og de metoder, du vil håndhæve som abstrakt uden faktisk at lægge nogen kode inde i disse metoder.

Derefter opretter du en underordnet klasse, der udvider den overordnede abstraktklasse og implementerer de abstrakte metoder i den underordnede klasse.

På denne måde vil du håndhæve alle barneklasser til at definere deres egen version af abstrakte metoder. Lad os se, hvordan vi kan indstille vores isActive()metode som abstrakt.

1: Definer klassen som abstrakt.


    

2: Create an abstract method for the method you want to enforce inside the abstract class.


     

3: Create a child class extending the abstract class.


      

4: Implement the abstract method inside the child class.


       

5: Instantiate the child class (NOT the abstract class).

isActive(); // => I am a very active athlete.

Complete abstract class definition and implementation code:

name = $name; $this->age = $age; $this->height = $height; } public function giveFirmHandshakes() { return "I give firm handshakes."; } public function beStubborn() { return "I am stubborn."; } public function notPutToiletPaper() { return "It's not humanly possible to remember to put toilet paper rolls when they are finished"; } abstract public function isActive(); } class AthleticMan extends Man { public function isActive() { return "I am a very active athlete."; } } $jack = new AthleticMan('Jack', '26', '5 feet 6 inches'); echo $jack->isActive(); // => I am a very active athlete.

In this code, you will notice that isActive() abstract method is defined inside Man abstract class and it is implemented inside child class AthleticMan.

Now Man class cannot be instantiated directly to create an object.

isActive(); // => Fatal error: Uncaught Error: Cannot instantiate abstract class Man

Also, every child class of the abstract class (Man class) needs to implement all the abstract methods. Lack of such implementation will result in a fatal error.

isActive(); // => Fatal error: Class LazyMan contains 1 abstract method // => and must therefore be declared abstract or implement // => the remaining methods (Man::isActive)

By using abstract classes, you can enforce certain methods to be implemented individually by the child classes.

Interface

There is another Object Oriented Programming concept that is closely related to Abstract Classes called Interface.

The only difference between Abstract Classes and Interfaces is that in Abstract Classes, you can have a mix of defined methods (giveFirmHandshakes(), isStubborn(), etc.) and abstract methods (isActive()) inside the parent class. But in Interfaces, you can only define (not implement) methods inside the parent class.

Let’s see how we can convert Man abstract class above to an interface.

1: Define the interface with all the methods (use interface instead of class).


      

2: Create a class that implements the interface (use implements instead of extends).

This class must implement ALL the methods defined inside the interface including the constructor method.

name = $name; $this->age = $age; $this->height = $height; } public function giveFirmHandshakes() { return "I give firm handshakes."; } public function beStubborn() { return "I am stubborn."; } public function notPutToiletPaper() { return "It's not humanly possible to remember to put toilet paper rolls when they are finished"; } public function isActive() { return "I am a very active athlete."; } }

3: Instantiate the implementing class (AthleticMan)

isActive(); // => I am a very active athlete.

With interfaces, you need to keep in mind that:

  • The methods cannot be implemented inside the interface.
  • Variables (properties) cannot be defined inside the interface.
  • All the methods defined inside the interface need to be implemented in the child (implementing) class.
  • All the necessary variables need to be defined inside the child class.
  • Man interface enforces its implementing classes to implement all the methods in the interface.

So, what is the use of interfaces?

Can’t we just create a new class AthleticMan and create all the methods instead of implementing the interface?

This is where Design Patterns come into play.

Interfaces are used when there is a base class (Man) that wants to enforce you to do things (construct an object, giveFirmHandshakes, beStubborn, notPutToiletPaper and check if you are active) but doesn’t want to tell you exactly how to do it.

You can just go ahead and create implementing classes with implementations as you deem fit.

As long as all the methods are implemented, Man interface doesn’t care how.

We have gone over how and when to use abstract classes and interfaces in PHP. Using these OOP concepts to have classes with different functionality sharing the same base “blueprint” (abstract class or interface) is called Polymorphism.