程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php設計模式 裝飾器模式,php設計模式

php設計模式 裝飾器模式,php設計模式

編輯:關於PHP編程

php設計模式 裝飾器模式,php設計模式


裝飾器模式,可以動態地添加修改類的功能。

一個類提供了一項功能,如果要修改並添加額外的功能,傳統的編程模式需要寫一個子類繼承它,並重新實現類的方法。使用裝飾器模式,僅需要在運行時添加一個裝飾器對象即可實現,可以實現最大的靈活性。

DrawDecorator.php
<?php
namespace Baobab;
/**
 * Interface DrawDecorator
 * @package Baobab
 * 裝飾器接口,定義兩個方法,渲染畫布之前和之後可添加額外的能力
 */
interface DrawDecorator{
    function beforeDraw();
    function afterDraw();
}
Canvas.php
<?php
namespace Baobab;

/**
*Canvas類,繪制圖形
**/
class Canvas { public $data; protected $decorators = array(); //Decorator function init($width = 20, $height = 10) { $data = array(); for($i = 0; $i < $height; $i++) { for($j = 0; $j < $width; $j++) { $data[$i][$j] = '*'; } } $this->data = $data; } function addDecorator(DrawDecorator $decorator){ $this->decorators[] = $decorator; } function beforeDraw(){ foreach($this->decorators as $decorator){ $decorator->beforeDraw(); } } function afterDraw(){ $decorators = array_reverse($this->decorators); foreach($decorators as $decorator){ $decorator->afterDraw(); } } function draw() { $this->beforeDraw(); foreach($this->data as $line) { foreach($line as $char) { echo $char; } echo "<br />\n"; } $this->afterDraw(); } function rect($a1, $a2, $b1, $b2) { foreach($this->data as $k1 => $line) { if ($k1 < $a1 or $k1 > $a2) continue; foreach($line as $k2 => $char) { if ($k2 < $b1 or $k2 > $b2) continue; $this->data[$k1][$k2] = '&nbsp;'; } } } }
ColorDrawDecorator.php
<?php
namespace Baobab;
/**
*修改圖形顏色的裝飾器
*/ class ColorDrawDecorator implements \Baobab\DrawDecorator{ protected $color; function __construct($color = 'black'){ $this->color = $color; } function beforeDraw(){ echo "<div style='color: {$this->color};'>"; }
function afterDraw(){ echo "</div>"; } }
SizeDrawDecorator.php
<?php
namespace Baobab;
/**
*修改圖形大小的裝飾器
*/ class SizeDrawDecorator implements \Baobab\DrawDecorator{ protected $size; function __construct($size = '12px'){ $this->size = $size; } function beforeDraw() { echo "<div style='font-size: {$this->size};'>"; }
function afterDraw() { echo "</div>"; } }

index.php

$canvas = new Baobab\Canvas();
$canvas->init();
$canvas->rect(3, 6,4,12);

$canvas->addDecorator(new \Baobab\ColorDrawDecorator('blue'));
$canvas->addDecorator(new \Baobab\SizeDrawDecorator('10px'));
......
//可添加其他更多裝飾器
$canvas->draw();

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved