<?php /** * 1.装饰器模式可以动态地 添加修改类的功能 * 2.1个类完成一个功能如果要修改添加额外的功能,传统的编程模式需要写一个子类继承他,并重新实现类的方法 * 3.使用装饰器模式,仅需在运行时添加-个装饰器对象即可实现,可以实现最大的灵活性 */ interface DrawDecorator{ public function afterDraw(); public function beforeDraw(); } class Dec implements DrawDecorator{ public function __construct($color = 'red'){ $this->color = $color; } public function afterDraw() { echo '</div>'; } public function beforeDraw() { echo "<div style = 'color:{$this->color};'>"; } } class Dec2 implements DrawDecorator{ public function __construct($size = '20'){ $this->size = $size; } public function afterDraw() { echo '</div>'; } public function beforeDraw() { echo "<div style = 'font-size:{$this->size};'>"; } } class Canvas { public $data; protected $decorators = array(); //初始化画布 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] = ' '; } } } } $prototype = new Canvas(); $prototype->init(); $prototype->addDecorator(new Dec()); //原型模式 $ca1 = clone $prototype; $ca1->rect(3, 6, 4, 12); $ca1->draw(); echo '<br/>'; $prototype->addDecorator(new Dec2()); $ca2= clone $prototype; $ca2->rect(1, 3, 2, 6); $ca2->draw();
php 设计模式(装饰器模式和原型模式组合)
最新推荐文章于 2021-09-21 21:13:58 发布