今天多少号了,家装效果图大全,五环童话伴奏
装饰器模式(decorator):动态的给一个对象添加一些额外的职责,就增加功能来说,装饰器比生成子类更加灵活。
这里以一个游戏角色为例,角色本身自带基础攻击属性,也可以通过额外的武器装备增加属性值。这里的装备武器就是动态的给角色添加额外的职责。
1、角色role.php,对应component
/** * 角色,抽象类 * class role */ abstract class role { /** * @return mixed */ abstract public function getname(); /** * @return mixed */ abstract public function getaggressivity(); }
2、武器arms.php,对应concretecomponent
/** * 武器,继承抽象类 * class arms */ class arms extends role { /** * 基础攻击力 * @var int */ private $aggressivity = 100; /** * @return string */ public function getname() { // todo: implement getname() method. return '基础攻击值'; } /** * @return int */ public function getaggressivity() { // todo: implement getaggressivity() method. return $this->aggressivity; } }
3、装饰抽象类roledecorator.php,对应decorator
/** * 装饰抽象类 * class roledecorator */ abstract class roledecorator extends role { /** * @var role */ protected $role; /** * roledecorator constructor. * @param role $role */ public function __construct(role $role) { $this->role = $role; } }
4、剑sword.php,对应concretedecorator
/** * 剑,具体装饰对象,继承装饰抽象类 * class sword */ class sword extends roledecorator { /** * @return mixed|string */ public function getname() { // todo: implement getname() method. return $this->role->getname() . '+斩妖剑'; } /** * @return int|mixed */ public function getaggressivity() { // todo: implement getaggressivity() method. return $this->role->getaggressivity() + 200; } }
5、枪gun.php,对应concretedecorator
/** * 枪,具体装饰对象,继承装饰抽象类 * class gun */ class gun extends roledecorator { /** * @return mixed|string */ public function getname() { // todo: implement getname() method. return $this->role->getname() . '+震天戟'; } /** * @return int|mixed */ public function getaggressivity() { // todo: implement getaggressivity() method. return $this->role->getaggressivity() + 150; } }
6、调用
// 基础攻击值 $arms = new arms(); echo $arms->getname(); echo $arms->getaggressivity() . '<br>'; // 基础攻击值+斩妖剑 $sword = new sword(new arms()); echo $sword->getname(); echo $sword->getaggressivity() . '<br>'; // 基础攻击值+震天戟 $gun = new gun(new arms()); echo $gun->getname(); echo $gun->getaggressivity() . '<br>'; // 基础攻击值+斩妖剑+震天戟 $person = new gun(new sword(new arms())); echo $person->getname(); echo $person->getaggressivity() . '<br>';
7、结果:
基础攻击值100 基础攻击值+斩妖剑300 基础攻击值+震天戟250 基础攻击值+斩妖剑+震天戟450
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
java多线程定时器和java判断一个时间是否在时间区间内和用正则表达式获取String字符串之间的数据
网友评论