Abstract Factory Pattern

<?php

/* ~~~~~~~~~~~~~ Factory Classes ~~~~~~~~~~~~~ */

abstract class RobotFactory{
abstract function build_male_robot();
abstract function build_female_robot();
}

class WorkRobotFactory extends RobotFactory{
function build_male_robot(){ return new MaleRobot('Work'); }
function build_female_robot(){ return new FemaleRobot('Work'); }
}

class EntertainmentRobotFactory extends RobotFactory{
function build_male_robot(){ return new MaleRobot('Entertainment'); }
function build_female_robot(){ return new FemaleRobot('Entertainment'); }
}

/* ~~~~~~~~~~~~~ Robots ~~~~~~~~~~~~~ */

abstract class Robot{
abstract function get_gender();
abstract function get_type();
}

class MaleRobot extends Robot{
private $_gender,$_type;
function __construct($type){
$this->_gender = "Male";
$this->_type = $type;
}
public function get_gender(){ return $this->_gender; }
public function get_type(){ return $this->_type; }
}

class FemaleRobot extends Robot{
private $_gender,$_type;
function __construct($type){
$this->_gender = "Female";
$this->_type = $type;
}
public function get_gender(){ return $this->_gender; }
public function get_type(){ return $this->_type; }
}

/* ~~~~~~~~~~~~~ Creator Class ~~~~~~~~~~~~~ */

class RobotFactoryCreator{
const WORK = "Work Robot";
const ENTERTAINMENT = "Entertainment Robot";

public static function CreateRobotFactory($factory_type){
switch($factory_type){
case self::WORK :
return new WorkRobotFactory();
break;
case self::ENTERTAINMENT :
return new EntertainmentRobotFactory();
break;
}
}
}

echo '~~~~~~~~~~~~~ Abstract Factory Example: ~~~~~~~~~~~~~';

//Direct Build
$entertainment_robot_factory = new WorkRobotFactory();
$male_bot = $entertainment_robot_factory->build_male_robot();
echo '<pre>';
var_dump($male_bot);
echo '</pre><br>';

//Creator Build
$entertainment_robot = RobotFactoryCreator::CreateRobotFactory(RobotFactoryCreator::ENTERTAINMENT);
$female_bot = $entertainment_robot->build_female_robot();

echo '<pre>';
var_dump($female_bot);
echo '</pre><br>';

?>

0 Comments

You must be logged in to post a comment.