Subscribe

RSS Feed (xml)

OOP Pattern - Factory: Simple Factory Pattern

PHP Factory Pattern Step By Step Tutorial - Part 1: In Object Oriented Programming, we always create new object with new operator. And in some cases, we need call same class for different steps. We can create a factory to avoid always call same class. The factory pattern encapsulates the creation of objects.
This is simple example that we always create new object every function that need it.


01<?php
02class Vehicle{
03 
04  function category($wheel = 0){
05    if($wheel == 2){
06        return "Motor";
07    }elseif($wheel == 4){
08        return "Car";
09    }
10  }
11}
12 
13class Spec{
14     
15  var $wheel = '';
16     
17  function Spec($wheel){
18    $this->wheel = $wheel;  
19  }
20     
21  function name(){
22    $wheel = $this->wheel;
23    return Vehicle::category($wheel);
24  }
25 
26  function brand(){
27    $wheel = $this->wheel; 
28    $kind =& Vehicle::category($wheel);
29    if($kind == "Motor"){
30        return array('Harley','Honda');
31    }elseif($kind = "Car"){
32        return array('Nisan','Opel');  
33    }
34  }
35     
36}
37 
38$kind = new Spec(2);
39echo "Kind: ".$kind->name();
40echo "<br>";
41echo "Brand: ".implode(",",$kind->brand());
42?>


This picture show how to implement factory pattern:
 This is complete code after changing (implement factory pattern)

01<?php
02class Vehicle{
03 
04  function category($wheel = 0){
05    if($wheel == 2){
06        return "Motor";
07    }elseif($wheel == 4){
08        return "Car";
09    }
10  }
11}
12 
13class Spec{
14     
15  var $wheel = '';
16  var $vc    = '';
17     
18  function Spec($wheel){
19    $this->wheel = $wheel;
20    $this->_getVehicle();
21  }
22   
23  function &_getVehicle(){
24    $wheel = $this->wheel;
25    $this->vc =& Vehicle::category($wheel);
26  }
27     
28  function name(){
29    return $this->vc;
30  }
31 
32  function brand(){
33    if($this->vc == "Motor"){
34        return array('Harley','Honda');
35    }elseif($this->vc = "Car"){
36        return array('Nisan','Opel');  
37    }
38  }
39     
40}
41 
42$kind = new Spec(2);
43echo "Kind: ".$kind->name();
44echo "<br>";
45echo "Brand: ".implode(",",$kind->brand());
46?>


In this practice, we create a factory within the object itself.  

0 comments:

Related Posts with Thumbnails