This is simple example that we always create new object every function that need it.
01 | <?php |
02 | class 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 |
13 | class 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); |
39 | echo "Kind: ".$kind->name(); |
40 | echo "<br>"; |
41 | echo "Brand: ".implode(",",$kind->brand()); |
42 | ?> |
This picture show how to implement factory pattern:
This is complete code after changing (implement factory pattern)
01 | <?php |
02 | class 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 |
13 | class 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); |
43 | echo "Kind: ".$kind->name(); |
44 | echo "<br>"; |
45 | echo "Brand: ".implode(",",$kind->brand()); |
46 | ?> |
In this practice, we create a factory within the object itself.

No comments:
Post a Comment