I tried to follow the factory design pattern but something is wrong. Maybe somebody could explain to me what I am doing wrong. I tried to create a class where the space to be populated with asteroids and spaceships but with no luck. I don't know how to create a concrete creator class.
<?php
//concrete prod 1
class Asteroid
{
private $size;
private $speed;
//bigger means faster
const SPEED_COEFICIENT = 2;
public function __construct( $size )
{
$this->size = $size;
$this->speed = $this->setSpeed();
}
private function setSpeed()
{
return $this->size * self::SPEED_COEFICIENT;
}
public function getSpeed()
{
return $this->speed;
}
}
//concrete product 2
class Spaceship
{
private $size;
private $speed;
//bigger means slower
const SPEED_COEFICIENT = 0.5;
public function __construct($size)
{
$this->size = $size;
$this->speed = $this->setSpeed();
}
private function setSpeed()
{
return $this->size * self::SPEED_COEFICIENT;
}
public function getSpeed()
{
return $this->speed;
}
}
interface SpaceFactory
{
public function createSpaceObject( $size);
}
class SpaceShipFactory implements SpaceFactory
{
public function createSpaceObject( $size)
{
return new Spaceship($size) ;
}
}
class AsteroidFactory implements SpaceFactory
{
public function createSpaceObject( $size)
{
return new Asteroid($size) ;
}
}
$asteroidFactory = new AsteroidFactory ();
$asteroid = $asteroidFactory->createSpaceObject(50);
var_dump($asteroid);
Thank you very much
Aucun commentaire:
Enregistrer un commentaire