私はYouTubeのビデオからデコレータパターンを学ぶことを試みてきました。私はおそらく初等OOPである何かに少し混乱しています。デコレータパターンのメソッドコール
以下のコードでは、$ p-> getDescription()に1つのメソッド呼び出し(コードの最後を参照)を行います。
$ p = new cheese(new sauce(new plainPizza))で作成されたすべてのクラスから連結された文字列を返します。
しかし、私はget_class($ p)のチーズクラスを実行します。では、チーズクラスのメソッド呼び出し(つまり、$ p-> getDescription())はすべてのクラスにどのように伝播しますか?なぜチーズクラスのgetDescriptionメソッドが呼び出されないのですか?
<?php
interface Pizza{
public function getDescription();
public function getCost();
}
class plainPizza implements Pizza{
public function getDescription(){
return 'Thin dough ';
}
public function getCost(){
return 4;
}
}
abstract class ToppingDecorator implements Pizza{
protected $pizza;
public function __construct(Pizza $pizza){
$this->pizza = $pizza;
}
}
class cheese extends ToppingDecorator{
public function __construct(Pizza $pizza){
parent::__construct($pizza);
}
public function getDescription(){
return $this->pizza->getDescription() . ' and adding cheeeeeese!';
}
public function getCost(){
return $this->pizza->getCost() + 0.55;
}
}
class sauce extends ToppingDecorator{
public function __construct(Pizza $pizza){
parent::__construct($pizza);
}
public function getDescription(){
return $this->pizza->getDescription() . ' and adding sauce ';
}
public function getCost(){
return $this->pizza->getCost() + 1.25;
}
}
$p = new cheese(new sauce(new plainPizza));
echo '<br>';
echo $p->getDescription(); //return Thin dough and adding sauce and adding cheeeeeese!
echo '<br>';
echo get_class($p); //return cheese
応答dbuggerに感謝します。私はまだちょっと混乱している。どのようなメカニズムによって、すべてのgetDesceiptionメソッドが呼び出されますか?チーズクラスのメソッドだけが明示的に呼び出されているので、他のすべてのクラスをカスケードするのはなぜですか?申し訳ありませんが、遅い場合は、私が観察できるものより詳細に何が起こっているのかを理解することが本当に熱心です。 – Drongo
魔法の仕組みはありません、コードに従ってください。 ** cheese **のgetDescription()メソッドを見てください。メソッドの最初のことは何ですか? **ソース**のgetDescriptionメソッドを呼び出します。メソッドの最初のことは何ですか? **ピザ**のgetDescriptionメソッドを呼び出します。ロギングを追加するかどうかを理解するのに役立ちます。 – dbugger
dbuggerに感謝します。ペニーは実際にあなたの最後のコメントから落としました。それを見ると、チーズgetDescriptionはピザオブジェクトgetDeacriptionが返すまで戻ることができないことがわかります。明快にする時間をとってくれてありがとう。 – Drongo