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.
04 | function category( $wheel = 0){ |
17 | function Spec( $wheel ){ |
18 | $this ->wheel = $wheel ; |
22 | $wheel = $this ->wheel; |
23 | return Vehicle::category( $wheel ); |
27 | $wheel = $this ->wheel; |
28 | $kind =& Vehicle::category( $wheel ); |
30 | return array ( 'Harley' , 'Honda' ); |
31 | } elseif ( $kind = "Car" ){ |
32 | return array ( 'Nisan' , 'Opel' ); |
39 | echo "Kind: " . $kind ->name(); |
41 | echo "Brand: " .implode( "," , $kind ->brand()); |
This picture show how to implement factory pattern:
This is complete code after changing (implement factory pattern)
04 | function category( $wheel = 0){ |
18 | function Spec( $wheel ){ |
19 | $this ->wheel = $wheel ; |
23 | function &_getVehicle(){ |
24 | $wheel = $this ->wheel; |
25 | $this ->vc =& Vehicle::category( $wheel ); |
33 | if ( $this ->vc == "Motor" ){ |
34 | return array ( 'Harley' , 'Honda' ); |
35 | } elseif ( $this ->vc = "Car" ){ |
36 | return array ( 'Nisan' , 'Opel' ); |
43 | echo "Kind: " . $kind ->name(); |
45 | echo "Brand: " .implode( "," , $kind ->brand()); |
In this practice, we create a factory within the object itself.
0 comments:
Post a Comment