设计模式之Item Render

Pattern name: Item Render

Motivation: 对于包含多Item的UI Component(如Tree, Table, DataGrid, etc) Item Containers来说,其行为大多固定,需要时常改变的是Item的显示。如果将显示实现放在这些item containers的class内,那么不仅这些classes的可重复利用性受到破坏,代码也难以管理。这时应该考虑将item的显示逻辑分离出来。

Approach: 将item显示逻辑独立出来放到item render class/function中。

Examples:
Java Swing及Flex的API中有大量的使用。Jack在这里举一个PHP的例子。在网站制作时,我们使用如下的HTML代码搭配CSS来显示导航:

<ul>
<li ><a href="A.php">A</a>
<ul><li ><a href="A1.php">A1</a></li><li ><a href="A2.php">A2</a></li></ul>
<li ><a href="B.php">B</a>
<ul><li ><a href="B1.php">B1</a></li><li ><a href="B2.php">B2</a></li></ul>
<li ><a href="C.php">C</a>
<ul><li ><a href="C1.php">C1</a></li><li ><a href="C2.php">C2</a></li></ul>
</ul>

在PHP中,我们使用Node来为如上的tree建模 - 有一个顶级的虚拟Node, 然后回溯打印即可。为了美化页面,这时我们想让第一级的Node显示图片,让其他级的保留使用文字。这时我们使用如下的render function:

// node class中:
public function toHtmlMenu($printThis = true, $printSubItemsLevel = 100, $renderFuncForListItemContent = NULL) {
  if($printThis) {
    $s = "<li>";
    if($renderFuncForListItemContent == null) {
        $s .= "<a href=\"$this->path\">" . $this->getLabel(). "</a>";
    }else{
        $s .= call_user_func($renderFuncForListItemContent, $this, $selectIndex, $language, $country);
    }
  }
  // recursive print ...
}

// in caller script:
function menuItemRenderLevel1AsImage(MenuItem $menuItem) {
   if($menuItem->getLevel() == 1) {
    return "<a href=\"" . $menuItem->getPath() . "\">" .  "<img src=\"$menuItem->id.png\">" . "</a>";
   }else{
    return "<a href=\"$this->path\">" . $this->getLabel(). "</a>";
   }
}

$menuCode = $MENU_ROOT->toHtmlMenu(false, 2, "menuItemRenderLevel1AsImage");