####PHP装饰器设计模式
装饰器模式就是对一个已有的结构增加“装饰”。对于适配器模式,为现有结构增加的是一个适配器类,用来处理不兼容的接口
为现有对象增加新功能而不影响其他对象,就可以使用装饰器模式
/**
* Created by PhpStorm.
* User: gewenrui
* Date: 16/3/9
* Time: 上午8:40
*/
abstract class IComponet{
protected $site;
abstract public function getSite();
abstract public function getPrice();
}
//扩展另一个抽象类
//维护组建接口
abstract class Decorator extends IComponet{
protected $data;
public function getSite()
{
return $this->site = "fuck";
}
}
//继承抽象方法并实现
class BasicSite extends IComponet{
public function __construct()
{
$this->site = "Basic site";
}
public function getSite()
{
return $this->site;
}
public function getPrice()
{
return 1200;
}
}
//继承装饰器
class Maintenance extends Decorator{
public function __construct(IComponet $siteNow)
{
$this->site = $siteNow;
}
public function getSite()
{
$fmat = "
Maintenance";
return $this->site->getSite().$fmat."";
}
public function getPrice()
{
return $this->site->getPrice() + 950;
}
}
//添加一个视频装饰器
class Video extends IComponet{
public function __construct(IComponet $siteNow){
$this->site = $siteNow;
}
public function getSite()
{
$fmat = "Video";
return $this->site->getSite().$fmat."";
}
public function getPrice()
{
return 350 +$this->site->getPrice();
}
}
//添加一个数据库装饰器
class Database extends IComponet{
public function __construct(IComponet $siteNow)
{
$this->site = $siteNow;
}
public function getSite()
{
$fmat = "database";
return $this->site->getSite().$fmat."";
}
public function getPrice()
{
return 800+$this->site->getPrice();
}
}
class Client{
private $basicSite;
public function __construct()
{
$this->basicSite = new BasicSite();
$this->basicSite = $this->wrapComponent($this->basicSite);
$siteShow = $this->basicSite->getSite();
$format = "totalL";
$price = $this->basicSite->getPrice();
echo $siteShow.$format.$price;
}
//实例化对象
private function wrapComponent(IComponet $componet){
$componet = new Maintenance($componet);
$componet = new Video($componet);
$componet = new Database($componet);
return $componet;
}
}
$data = new Client();