PHP设计模式(八)装饰器模式Decorator实例详解【(4)
增加一些css样式后,表单渲染出来如下图所示:

我们使用装饰器代码:
<?php
/**
* 装饰器模式的组成:
* 抽象组件角色(Component):定义一个对象接口,以规范准备接受附加责任的对象,即可以给这些对象动态地添加职责。
* 具体组件角色(ConcreteComponent) :被装饰者,定义一个将要被装饰增加功能的类。可以给这个类的对象添加一些职责。
* 抽象装饰器(Decorator):维持一个指向构件Component对象的实例,并定义一个与抽象组件角色Component接口一致的接口。
* 具体装饰器角色(ConcreteDecorator): 向组件添加职责。
* @author guisu
* @version 1.0
*/
/**
* 抽象组件角色(Component)
*
*/
class ComponentWidget {
function paint() {
return $this->_asHtml();
}
}
/**
*
* 具体组件角色(ConcreteComponent):
* 让我们以一个基本的text输入组件开始。它(组件)必须要包含输入区域的名字(name)而且输入内容可以以HTML的方式渲染。
*
*/
class ConcreteComponentTextInput extends ComponentWidget {
protected $_name;
protected $_value;
function TextInput($name, $value='') {
$this->_name = $name;
$this->_value = $value;
}
function _asHtml() {
return '<input type="text" name="'.$this->_name.'" value="'.$this->_value.'">';
}
}
/**
* 抽象装饰器(Decorator):维持一个指向构件Component对象的实例,并定义一个与抽象组件角色Component接口一致的接口。
*
* 我们进入有能够统一增加(一些特性)能力的装饰器模式。
* 作为开始,我们建立一个普通的可以被扩展产生具体的特定装饰器的WidgetDecorator类。至少WidgetDecorator类应该能够在它的构造函数中接受一个组件,
* 并复制公共方法paint()
*
*/
class WidgetDecorator {
protected $_widget;
function __construct( &$widget) {
$this->_widget = $widget;
}
function paint() {
return $this->_widget->paint();
}
}
/**
* 具体装饰器角色(ConcreteDecorator):
* 为建立一个标签(lable),需要传入lable的内容,以及原始的组件
* 有标签的组件也需要复制paint()方法
*
*/
class ConcreteDecoratorLabeled extends WidgetDecorator {
protected $_label;
function __construct($label, &$widget) {
$this->_label = $label;
parent::__construct($widget);
}
function paint() {
return '<b>'.$this->_label.':</b> '.$this->_widget->paint();
}
}
/**
* 实现
*
*/
class FormHandler {
function build(&$post) {
return array(
new ConcreteDecoratorLabeled('First Name', new ConcreteComponentTextInput('fname', $post->get('fname')))
,new ConcreteDecoratorLabeled('Last Name', new ConcreteComponentTextInput('lname', $post->get('lname')))
,new ConcreteDecoratorLabeled('Email', new ConcreteComponentTextInput('email', $post->get('email')))
);
}
}
/**
* 通过$_post提交的数据
*/
class Post {
private $store = array();
function get($key) {
if (array_key_exists($key, $this->store))
return $this->store[$key];
}
function set($key, $val) {
$this->store[$key] = $val;
}
static function autoFill() {
$ret = new self();
foreach($_POST as $key => $value) {
$ret->set($key, $value);
}
return $ret;
}
}
?>
内容版权声明:除非注明,否则皆为本站原创文章。
