Context
I'm looking into design patterns. My first try is using the Decorator Pattern.
Question:
Is there another (maybe standard) approach to applying modifications in a decorator other than explicitly overwriting in the constructor? -
Car Interface
<?php
interface CarInterface
{
public function drive();
}
Care Base Class
<?php
class CarBaseClass implements CarInterface
{
public $model = 'Base Model';
public $top_speed = null;
public $features = ['AC', 'Radio'];
public function __construct($top_speed)
{
$this->top_speed = $top_speed;
}
public function drive(): void
{
echo $this->model . " speed: " . $this->top_speed;
}
}
Tesla
<?php
class Tesla extends CarBaseClass
{
public $model = 'Tesla';
}
Engine Feature Decorator
<?php
class V20Engine extends CarBaseClass
{
public $SPEED_BOOST = 1.5;
public $new_features = ['V20 Engine'];
public function __construct(CarBaseClass $car)
{
$this->model = 'V20 ' . $car->model;
$this->top_speed = $car->top_speed * $this->SPEED_BOOST;;
$this->features = array_merge($car->features, $this->new_features);
}
}
Turbo Decorator
<?php
class TurboEnabled extends CarBaseClass
{
public $TURBO_BOOST = 1.75;
public $new_features = ['Turbo Enabled', 'Snoop Dog GPS'];
public function __construct(CarBaseClass $car)
{
$this->model = 'Turbo Enabled ' . $car->model;
$this->top_speed = $car->top_speed;
$this->features = array_merge($car->features, $this->new_features);
}
public function activateTurbo() {
$this->top_speed = $this->top_speed * $this->TURBO_BOOST;
return $this;
}
}
index.php
<?php
require 'classes/Car/CarInterface.php';
require 'classes/Car/CarBaseClass.php';
require 'classes/Car/Tesla.php';
require 'classes/Car/Feature/TurboEnabled.php';
require 'classes/Car/Feature/V20Engine.php';
echo "<pre>";
$tesla = new Tesla(100);
$tesla->drive();
echo "<br>";
$turbo_tesla = new TurboEnabled($tesla);
$turbo_tesla->activateTurbo()->drive();
echo "<br>";
$v20_tesla = new V20Engine($tesla);
$v20_tesla->drive();
echo "<br>";
$v20_turbo_tesla = new V20Engine($turbo_tesla);
$v20_turbo_tesla->drive();
echo "<br>";
$car = new V20Engine( new TurboEnabled( new CarBaseClass(100) ) );
print_r( $car->features );