DesignPatternsPHP/FactoryMethod/FactoryMethod.php

54 lines
1.3 KiB
PHP
Raw Normal View History

2013-05-10 21:09:55 +02:00
<?php
/*
* DesignPatternPHP
*/
namespace DesignPatterns\FactoryMethod;
/**
2013-05-10 21:29:43 +02:00
* FactoryMethod is a factory method. The good point over the SimpleFactory
2013-05-10 21:09:55 +02:00
* is you can subclass it to implement different way to create vehicle for
2013-05-10 21:29:43 +02:00
* each country (see subclasses)
2013-05-10 21:09:55 +02:00
*
2013-05-10 21:29:43 +02:00
* For simple case, this abstract class could be just an interface
*
* This pattern is a "real" Design Pattern because it achieves the
* "Dependency Inversion Principle" a.k.a the "D" in S.O.L.I.D principles.
*
* It means the FactoryMethod class depends on abstractions not concrete classes.
* This is the real trick compared to SImpleFactory or StaticFactory.
2013-05-10 21:09:55 +02:00
*/
abstract class FactoryMethod
{
2013-05-10 21:29:43 +02:00
const CHEAP = 1;
const FAST = 2;
2013-05-10 21:09:55 +02:00
/**
* The children of the class must implement this method
*
* Sometimes this method can be public to get "raw" object
*
* @param string $type a generic type
*
* @return Vehicle a new vehicle
*/
abstract protected function createVehicle($type);
/**
* Creates a new vehicle
*
2013-05-10 21:29:43 +02:00
* @param int $type
2013-05-10 21:09:55 +02:00
*
* @return Vehicle a new vehicle
*/
public function create($type)
{
$obj = $this->createVehicle($type);
$obj->setColor("#f00");
return $obj;
}
}