PHP设计模式(八)装饰器模式Decorator实例详解【结构型】
/** * 实现 * */ 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'))) ); } function validate(&$form, &$post) { $valid = true; // first name required if (!strlen($post->get('fname'))) { $form[0] =& new Invalid($form[0]); $valid = false; } // last name required if (!strlen($post->get('lname'))) { $form[1] =& new Invalid($form[1]); $valid = false;} // email has to look real if (!preg_match('~w+@(w+.)+w+~' ,$post->get('email'))) { $form[2] =& new Invalid($form[2]); $valid = false; } return $valid; } } 最后功效: <html> <head> <title>Decorator Example</title> <style type="text/css"> .invalid {color: red; } .invalid input { background-color: red; color: yellow; } #myform input { position: absolute; left: 110px; width: 250px; font-weight: bold;} </style> </head> <body> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post"> <div> <?php $pos =& Post::autoFill(); $form = FormHandler::build($post); if ($_POST) { FormHandler::validate($form, $post); } foreach($form as $widget) { echo $widget->paint(), "<br>n"; } ?> </div> <input type="submit" value="Submit"> </form> </body> </html> 9. 装饰器模式与其他相干模式1)Adapter 模式:Decorator模式差异于Adapter模式,由于装饰仅改变工具的职责而 2)Composite模式:可以将装饰视为一个退化的、仅有一个组件的组 3)Strategy模式:用一个装饰你可以改变工具的外表;而Strategy模 1)行使装饰器计划模式计划类的方针是: 不必重写任何已有的成果性代码,而是对某个基于工具应用增量变革。 2) 装饰器计划模式回收这样的构建方法: 在主代码流中应该可以或许直接插入一个或多个变动或“装饰”方针工具的装饰器, 同时不影响其他代码流。 3) Decorator模式回收工具组合而非担任的伎俩,实现了在运行时动态的扩展工具成果的手段, 并且可以按照必要扩展多个成果,停止了单独行使担任带来的“机动性差”和“多子类衍生题目”。 同时它很好地切合面向工具计划原则中“优先行使工具组合而非担任”和“开放-关闭”原则。 大概装饰器模式最重要的一个方面是它的高出担任的手段。“题目”部门揭示了一个行使担任的子类爆炸。 基于装饰器模式的办理方案,UML类图揭示了这个简捷机动的办理方案。 更多关于PHP相干内容感乐趣的读者可查察本站专题:《php面向工具措施计划入门教程》、《PHP数组(Array)操纵能力大全》、《PHP根基语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操纵入门教程》及《php常见数据库操纵能力汇总》 (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |