Kompositum Entwurfsmuster in PHP5
<?php // Kompositum.interface.php5 Interface IKompositum { public function get ( ); } ?>
<?php // Kompositum.class.php5 class Kompositum implements IKompositum { private $children; function __construct ( ) { $this->children = array(); } public function get ( ) { $result = NULL; if( count($this->children) >= 1 ) while( list(,$instance) = each($this->children) ) { $result .= $instance->get(); } return $result; } public function add ( $instance ) { $this->children[] = $instance; } public function remove ( $instance ) { } } ?>
<?php // Child.class.php5 class Child implements IKompositum { private $content; function __construct ( ) { $this->content = NULL; } public function get ( ) { return $this->content; } public function set ( $content ) { $this->content = $content; } public function remove ( ) { $this->content = NULL; } } ?>
<?php include_once('Kompositum.interface.php5'); include_once('Kompositum.class.php5'); include_once('Child.class.php5'); $kompositum1 = new Kompositum(); $kompositum2 = new Kompositum(); $kompositumAll = new Kompositum(); $child1 = new Child(); $child1->set("Das "); $child2 = new Child(); $child2->set("ist "); $child3 = new Child(); $child3->set("der "); $child4 = new Child(); $child4->set("erste "); $child5 = new Child(); $child5->set("Satz "); $kompositum1->add($child1); $kompositum1->add($child2); $kompositum2->add($child3); $kompositum2->add($child4); $kompositum2->add($child5); $kompositumAll->add($kompositum1); $kompositumAll->add($kompositum2); echo $kompositumAll->get(); ?>
// Ausgabe: Das ist der erste Satz