phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


OOP Pattern - Factory: Promoting Polymorphism

Tag: oop, pattern, factory pattern, polymorphism   Category: PHP Classes
post: 19 Feb 2008 read: 209


PHP Factory Pattern Step By Step Tutorial - Part 5: We can use power of factory pattern by create one interface for returning objects of varying classes.

<?php
class CarFactory{
  function carBrand($brand){ }
}

class HondaFactory extends CarFactory{
  var $context = "Honda";
  
  function carBrand($brand){    
	$car = NULL;	
    switch($brand){
	  case "self":
	    $car = new JazzCar;
		break;
	  case "rival":
	    $car = new LivinaCar;
	    break;
	  default:
	    $car = new JazzCar;
	    break;
	}
	
	return $car;
  }  
}

class NisanFactory extends CarFactory{
  var $context = "Nisan";
  
  function carBrand($brand){
    $car = NULL;
    switch($brand){
	  case "self":
	    $car = new LivinaCar;
		break;
	  case "rival":
	    $car = new JazzCar;
	    break;
	  default:
	    $car = new LivinaCar;
	    break;
	}
	
	return $car;	
  }
}

class AbstractCar{
  function getBrand(){  }
  function getColor(){  }
}

class AbstractBrandCar{
  var $subject = "Brand";
}

class JazzCar extends AbstractBrandCar{
  var $brand = 'Jazz';
  var $color = array('blue','yellow');
  
  function getBrand(){ return $this->brand; }
  function getColor(){ return $this->color; }  
  
}

class LivinaCar extends AbstractBrandCar{
  var $brand = 'Livina';
  var $color = array('metalic','red');
  
  function getBrand(){ return $this->brand; }
  function getColor(){ return $this->color; }  
  
}

$factoryInstance = new HondaFactory;
$car = $factoryInstance->carBrand('self');
echo "car name: ".$car->getBrand();
echo "</br>";
echo "available color: ".
      implode(",",$car->getColor());
	  
echo "<br>";	  
	  
$factoryInstance = new NisanFactory;
$car = $factoryInstance->carBrand('rival');
echo "car name: ".$car->getBrand();
echo "</br>";
echo "available color: ".
      implode(",",$car->getColor());	  

?>

Following image can brief us about our practice above.

polymorphism at factory pattern



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting