溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在PHP中實現(xiàn)一個裝飾器模式

發(fā)布時間:2021-04-15 15:59:26 來源:億速云 閱讀:126 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了如何在PHP中實現(xiàn)一個裝飾器模式,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

具體如下:

<?php
//裝飾器模式-在不改變原有類的結(jié)構(gòu)上,對類的功能那個作補充
//武器基類
abstract class Weapon{
  abstract public function descriptions();
  abstract public function cost();
}
//劍類
class Glave extends Weapon{
  public function descriptions(){
    return 'Glave';
  }
  public function cost(){
    return "100";
  }
}
//匕首類
class Knife extends Weapon{
  public function descriptions(){
    return __CLASS__;
  }
  public function cost(){
    return "80";
  }
}
//斧類
class Axe extends Weapon{
  public function descriptions(){
    return __CLASS__;
  }
  public function cost(){
    return "200";
  }
}
//屬性類
class Property extends Weapon{
  protected $_weapon = null;
  protected $_price = 0;
  protected $_descriptions = '';
  public function __construct(Weapon $weapon){
    $this->_weapon = $weapon;
  }
  public function cost(){
    return   $this->_weapon->cost() + $this->_price;
  }
  public function descriptions(){
    return $this->_weapon->descriptions().$this->_descriptions;
  }
}
//力量屬性
class Strength extends Property{
  protected $_price = 30;
  protected $_descriptions = '+ Strength';
}
//敏捷屬性
class Agility extends Property{
  protected $_price = 50;
  protected $_descriptions = '+ Agility';
}
//智力屬性
class Intellect extends Property{
  protected $_price = 20;
  protected $_descriptions = '+ Intellect';
}
$weapon = new Agility(new Strength(new Strength(new Glave())));
echo $weapon->cost();
echo $weapon->descriptions();

上述內(nèi)容就是如何在PHP中實現(xiàn)一個裝飾器模式,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI