« Patrons de conception/Objet composite » : différence entre les versions

Contenu supprimé Contenu ajouté
Aucun résumé des modifications
imported>Konandrum
Ajout d'un exemple du pattern en PHP 5, ajout d'un diagramme UML prochainement
Ligne 65 :
</source>
 
==Exemple Java==
 
L'exemple qui suit, écrit en [[Java (langage)|Java]], implémente une classe graphique qui peut être ou bien une ellipse ou une composition de différents graphiques. Chaque graphique peut être imprimé.
 
Ligne 143 :
</source>
 
==Exemple en PHP 5==
<source lang=php>
<?php
class Component
{
private $basePath;
private $name;
private $parent;
public function __construct($name, CDirectory $parent = null)
{
//echo "const Component";
$this->name = $name;
$this->parent = $parent;
if($this->parent != null)
{
$this->parent->addChild($this);
$this->basePath = $this->parent->getPath();
}
else
{
$this->basePath = '';
}
}
public function getBasePath() { return $this->basePath; }
public function getName() { return $this->name; }
public function getParent() { return $this->parent; }
public function setBasePath($basePath) { $this->basePath = $basePath; }
public function setName($name) { $this->name = $name; }
public function setParent(CDirectory $parent) { $this->parent = $parent; }
public function getPath() { return $this->getBasePath().'/'.$this->getName(); }
}
 
class CFile extends Component
{
private $type;
 
public function __construct($name, $type, CDirectory $parent = null)
{
$this->type = $type;
parent::__construct($name, $parent);
}
public function getType() { return $this->type; }
public function setType($type) { $this->type = $type; }
public function getName() { return parent::getName().'.'.$this->getType();
public function getPath() { return parent::getPath().'.'.$this->getType(); }
}
 
class CDirectory extends Component
{
private $childs;
public function __construct($name, CDirectory $parent = null)
{
$this->childs = array();
//echo "const CDirectory";
parent::__construct($name, $parent);
}
public function getChilds() { return $this->childs; }
public function setChilds($childs) { $this->childs = $childs; }
public function addChild(Component $child)
{
$child->setParent($this);
$this->childs[] = $child;
}
public function showChildsTree($level = 0)
{
echo "<br/>".str_repeat('&nbsp;', $level).$this->getName();
foreach($this->getChilds() as $child)
{
if($child instanceof self)
{
$child->showChildsTree($level+1);
}
else
{
echo "<br/>".str_repeat('&nbsp;', $level+1).$child->getName();
}
}
}
?>
</source>
 
[[Catégorie:Patron de conception]]