Codebeispiele: https://sourcemaking.com/design_patterns/composite/php Ich habe etwas ähnliches gemacht, außer dass "OnTheBookShelf
" über $ books (SeveralBooks
) bekannt ist. Mein "Chef" sagt es ist schlecht, dass sie voneinander wissen. Aber warum?Zusammengesetztes Muster, warum ist es schlecht, wenn "Kinder" von "Eltern" wissen?
Allright, ich kann es bearbeiten:
abstract class OnTheBookShelf {
public $shelf; /////////////////////////////////////////////////
abstract function getBookInfo($previousBook);
abstract function getBookCount();
abstract function setBookCount($new_count);
abstract function addBook($oneBook);
abstract function removeBook($oneBook);
}
class OneBook extends OnTheBookShelf {
private $title;
private $author;
function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}
function getBookInfo($bookToGet) {
if (1 == $bookToGet) {
return $this->title." by ".$this->author;
} else {
return FALSE;
}
}
function getBookCount() {
return 1;
}
function setBookCount($newCount) {
return FALSE;
}
function addBook($oneBook) {
return FALSE;
}
function removeBook($oneBook) {
return FALSE;
}
}
class SeveralBooks extends OnTheBookShelf {
private $oneBooks = array();
private $bookCount;
public function __construct() {
$this->setBookCount(0);
}
public function getBookCount() {
return $this->bookCount;
}
public function setBookCount($newCount) {
$this->bookCount = $newCount;
}
public function getBookInfo($bookToGet) {
if ($bookToGet <= $this->bookCount) {
return $this->oneBooks[$bookToGet]->getBookInfo(1);
} else {
return FALSE;
}
}
public function addBook($oneBook) {
$oneBook->shelf = $this; //////////////////////////////////////////////////
$this->setBookCount($this->getBookCount() + 1);
$this->oneBooks[$this->getBookCount()] = $oneBook;
return $this->getBookCount();
}
public function removeBook($oneBook) {
$counter = 0;
while (++$counter <= $this->getBookCount()) {
if ($oneBook->getBookInfo(1) ==
$this->oneBooks[$counter]->getBookInfo(1)) {
for ($x = $counter; $x < $this->getBookCount(); $x++) {
$this->oneBooks[$x] = $this->oneBooks[$x + 1];
}
$this->setBookCount($this->getBookCount() - 1);
}
}
return $this->getBookCount();
}
}
ich ein paar //////////////// zu den problematischen Zeilen hinzugefügt. Und hier sagen sie, dass das Buch einen Bezug zum Regal hat.
Bitte zeigen Sie ein konkretes Beispiel. In einem zusammengesetzten Muster gibt es normalerweise keine "Eltern/Kind" -Beziehung; Das bezieht sich auf die Klassenvererbung. Erweitert "Book Bookshelf" in Ihrem Fall * und "Bookshelf" besteht aus "Books", oder was ...? – deceze
bearbeitet. Bearbeitet. –