logo

PHP Factory Method Design Pattern

Code example for Factory Method in PHP

Category: PHP

by designzone

2015-05-02 22:29:17

Factory Method Design Pattern
Useful when the concrete products that need to be created are unknown.

BikeFactory.interface.php
/**
 * BikeFactory interface
 */
interface BikeFactory {
    public function makeBike();
}

Bike.interface.php
/**
 * Bike interface
 */
interface Bike {
    public function getType();
}

MountainBikeFactory.class.php
include "BikeFactory.interface.php";
include "MountainBike.class.php";

/**
 * MountainBikeFactory class
 */
class MountainBikeFactory implements BikeFactory {
    public function makeBike() {
        return new MountainBike();
    }
}

MountainBike.class.php
include "Bike.interface.php";

/**
 * MountainBike class
 */
class MountainBike implements Bike {
    public function getType() {
        return 'Mountain Bike';
    }
}

test.php
include "MountainBikeFactory.class.php";

$factory = new MountainBikeFactory();
$bike = $factory->makeBike();
$type_of_bike = $bike->getType();
echo "Bike Type: $type_of_bike<br>\n";

comments powered by Disqus