Last active
September 17, 2017 15:06
-
-
Save tkouleris/96e9395faa906f13fd624bfc4f84157d to your computer and use it in GitHub Desktop.
Composite Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| abstract class SongComposite{ | |
| public function songInfo(){} | |
| } | |
| class Song extends SongComposite{ | |
| private $songTitle; | |
| private $songBand; | |
| public function __construct($sTitle, $sBand){ | |
| $this->songTitle = $sTitle; | |
| $this->songBand = $sBand; | |
| } | |
| public function songInfo(){ | |
| return "Title: ".$this->songTitle."\r\n"."Band: ".$this->songBand."\r\n"; | |
| } | |
| } | |
| class SongGroup extends SongComposite{ | |
| private $Songs = array(); | |
| private $songCount; | |
| public function __construct(){ | |
| $this->songCount = 0; | |
| } | |
| public function addSong(SongComposite $s){ | |
| array_push($this->Songs,$s); | |
| $this->songCount++; | |
| } | |
| public function removeSong($index){ | |
| $index = $index--; //To match the array index | |
| if($index > $this->songCount){ | |
| echo $this->songCount; | |
| return; | |
| } | |
| unset($this->Songs[$index]); | |
| $this->songCount--; | |
| } | |
| public function songInfo(){ | |
| echo "\r\n"; | |
| foreach ($this->Songs as $Song) { | |
| echo $Song->songInfo(); | |
| echo "\r\n"; | |
| } | |
| } | |
| } | |
| $song1 = new Song("Heart of Steel","Manowar"); | |
| $song2 = new Song("Master of puppets","Metalica"); | |
| $song3 = new Song("Emerald Sword","Rhapsody"); | |
| $SongGroup = new SongGroup(); | |
| $SongGroup->addSong($song1); | |
| $SongGroup->addSong($song2); | |
| $SongGroup->addSong($song3); | |
| $SongGroup->songInfo(); | |
| $SongGroup->removeSong(2); | |
| echo "=============== After remove ==================\r\n"; | |
| $SongGroup->songInfo(); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment