(not design) pattern : simple factory

This commit is contained in:
Trismegiste
2013-05-10 20:22:43 +02:00
parent 87d4c9277d
commit 9b7330795d
5 changed files with 159 additions and 0 deletions

20
SimpleFactory/Bicycle.php Normal file
View File

@@ -0,0 +1,20 @@
<?php
/*
* DesignPatternPHP
*/
namespace DesignPatterns\SimpleFactory;
/**
* Bicycle is a bicycle
*/
class Bicycle implements Vehicle
{
public function driveTo($destination)
{
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*
* DesignPatternPHP
*/
namespace DesignPatterns\SimpleFactory;
/**
* ConcreteFactory is a simple factory pattern.
*
* It differs from the static factory because it is NOT static and as you
* know : static => global => evil
*
* Therefore, you can haZ multiple factories, differently parametrized,
* you can subclass it and you can mock-up it.
*/
class ConcreteFactory
{
protected $typeList;
/**
* You can imagine to inject your own type list or merge with
* the default ones...
*/
public function __construct()
{
$this->typeList = array(
'bicycle' => __NAMESPACE__ . '\Bicycle',
'other' => __NAMESPACE__ . '\Scooter'
);
}
/**
* Creates a vehicle
*
* @param string $type a known type key
* @return Vehicle a new instance of Vehicle
* @throws \InvalidArgumentException
*/
public function createVehicle($type)
{
if (!array_key_exists($type, $this->typeList)) {
throw new \InvalidArgumentException("$type is not valid vehicle");
}
$className = $this->typeList[$type];
return new $className();
}
}

20
SimpleFactory/Scooter.php Normal file
View File

@@ -0,0 +1,20 @@
<?php
/*
* DesignPatternPHP
*/
namespace DesignPatterns\SimpleFactory;
/**
* Scooter is a Scooter
*/
class Scooter implements Vehicle
{
public function driveTo($destination)
{
}
}

16
SimpleFactory/Vehicle.php Normal file
View File

@@ -0,0 +1,16 @@
<?php
/*
* DesignPatternPHP
*/
namespace DesignPatterns\SimpleFactory;
/**
* Vehicle is a contract for a vehicle
*/
interface Vehicle
{
function driveTo($destination);
}