Quantcast
Channel: The Code Collective » design patterns
Viewing all articles
Browse latest Browse all 7

Composite Pattern

$
0
0
<?php abstract class Horse{ abstract function get_horsepower(); } class Pony extends Horse{ public function get_horsepower(){ return 0.7; } } class RidingHorse extends Horse{ public function get_horsepower(){ return 1.0; } } class WarHorse extends Horse{ public function get_horsepower(){ return 1.5; } } /* ~~~~~~~~~~~~~ Wagons ~~~~~~~~~~~~~ */ class SmallWagon{ private $_horses = array(); public function add_horse(Horse $new_horse){ array_push($this->_horses,$new_horse); } public function get_horsepower(){ $total_horsepower = 0; foreach($this->_horses as $horse){ $total_horsepower += $horse->get_horsepower(); } return $total_horsepower - ($total_horsepower * 0.1); //10% Decrease } } class LargeWagon{ private $_horses = array(); public function add_horse(Horse $new_horse){ array_push($this->_horses,$new_horse); } public function get_horsepower(){ $total_horsepower = 0; foreach($this->_horses as $horse){ $total_horsepower += $horse->get_horsepower(); } return $total_horsepower - ($total_horsepower * 0.2); //20% Decrease } } echo '~~~~~~~~~~~~~ Composite Example: ~~~~~~~~~~~~~'; $wagon = new SmallWagon(); $wagon->add_horse(new WarHorse()); $wagon->add_horse(new WarHorse()); $wagon->add_horse(new Pony()); $lg_wagon = new LargeWagon(); $lg_wagon->add_horse(new WarHorse()); $lg_wagon->add_horse(new WarHorse()); $lg_wagon->add_horse(new Pony()); echo '<pre>'; print_r($wagon); echo 'Small Wagon HP: '; print_r($wagon->get_horsepower()); echo '<br>Large Wagon HP: '; print_r($lg_wagon->get_horsepower()); echo '</pre><br><br>'; ?>

Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles



Latest Images