Encapsulate different related algorithms.
The client that instantiate an algorithm have no knowledge of the implementation.
abstractclassAnimal{
public $flyBehavior;
}
interfaceFly{
publicfunctionfly();
}
classFlyBehaviorimplementsFly{
// @Overridepublicfunctionfly(){
return"It flies";
}
}
classNonFlyBehaviorimplementsFly{
// @Overridepublicfunctionfly(){
return"Can't fly";
}
}
classDogextendsAnimal{
publicfunction__construct(){
// This is call 'composition'// Instead of inheritance ...// the class is composed with different objects$this->flyBehavior = new NonFlyBehavior(); // Look Here
}
}
classBirdextendsAnimal{
publicfunction__construct(){
$this->flyBehavior = new FlyBehavior();
}
}
$dog = new Dog();
echo"Dog: " . $dog->flyBehavior->fly(); // Dog: Can't fly
$bird = new Bird();
echo"Bird: " . $bird->flyBehavior->fly(); // Bird: It flies
Runtime
Another great thing about composition:
It allows you to change capabilities of objects at runtime.
// the dog got wings
$dog->flyBehavior = new FlyBehavior();
echo"Dog: " . $dog->flyBehavior->fly(); // Dog: It flies !
Wrong Approach
The goal is to give to Bird (and other animals) the capability to fly.
Wrong approach is to add a method in the superclass.
This is bad when it isn't needed in every subclass.