This article introduces the content of the PHP design model of the decorative mode, has a certain reference value, now share to everyone, the need for friends can refer to
Decorative Mode (Decorator) is also one of the structural patterns, defined as: Dynamically adding some additional responsibilities to an object.
The most common example in our lives is the equipment, skins, of the characters that accompany the game at all times. I believe that no matter the boys and girls, play games have been bought.
One of the most common is the game developers, by doing some equipment, such as weapons, clothing, shoes, rings and so on, to attract players to buy, wear not only good-looking, but also with extra attributes.
This example is the application of the typical adorner pattern, which is characterized by the dynamic addition of other specific equipment classes without affecting other classes.
<?php/** Component Interface class * Interface IComponent */interface IComponent {function Displa Y (); }/** Character class * Person * */class implements IComponent {private $name; function __construct ($name) {$this->name = $name; } function Display () {echo "{$this->name} is currently equipped with:"; }}/** Equipment class * Equipment */class equipment implements IComponent {protected $component; function Decorator (IComponent $component) {//dynamically add $this->component = $component; } function Display () {if (!empty ($this->component)) {$this->component->display ( ); }}}/** specific weapon class * weapon */class weapon extends equipment {function Display () { Parent::D Isplay (); echo "Longquan sword"; }}/** specifically equipped ring class * ring */class ring extends Equipment {function Display () {parent::D isplay (); echo "Resurrection Ring"; }}/** specifically equipped with shoes class * Shoes */class Shoes extends Equipment {function Display () {Parent::D Isplay (); echo "Royal Wind"; }}//If necessary, you can continue to add specific equipment belt pants bracelet
<?php //Adorner mode index.php header ("Content-type:text/html;charset=utf-8"); Require_once "decorator.php"; Create a character $people = new Person ("warrior"); Weapon $Weapon = new Weapon (); Ring $Ring = new Ring (); Shoe $Shoes = new Shoes (); Dynamically add function $Weapon->decorator ($people); $Ring->decorator ($Weapon); $Shoes->decorator ($Ring); Display $Shoes->display ();
Output Result:
Warrior Current equipment: Longquan Sword Resurrection ring Royal Wind Shoes