您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP组合模式第一种实现方式

2024/2/29 21:04:41发布18次查看
php组合模式第一种实现方式
<?php // 组合模式 function echoline($msg) { echo $smg, '<br/>'; } interface component { public function doaction(); } /** * 局部类 */ class leaf implements component { public function doaction() { echoline('the [leaf] doaction!'); } } /** * 组合模式的一个问题是如何实现 add 和 remove 方法。一般的组合模式会在抽象超类中添加 add * 和 remove 方法。这可以确保模式中的所有类都共享同一个借口,但这同时也意味着局部类也必须 * 实现这些方法。实际上,我们并不希望在局部类中实现这些方法。 * * 需要担心的问题: * 1. 组合操作的成本。 * 2. 对象持久化问题。难以直接将数据保存在关系型数据中,但其数据却非常适合持久化为 xml。 */ class composite implements component { /** * component container */ private $container = array(); public function doaction() { echoline('the [composite] doaction!'); foreach ($this->container as $c) $c->doaction(); } /** * add component * @param component $c */ public function addcomponent(component $c) { if(!in_array($c, $this->container, true)) $this->container[] = $c; } /** * remove conponent * @param component $c */ public function removecomponent(component $c) { $this->container = array_diff($this->container, array($c)); } /** * get all components * @return array */ public function getcomponents() { return $this->container; } } // test code $leaf = new leaf(); $composite = new composite(); $composite->addcomponent($leaf); $composite->addcomponent(new leaf()); $composite->addcomponent(new leaf()); $composite->doaction();
以上就是php组合模式第一种实现方式的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product