给定一个叶子及其父TD,进行打印:
$parent = new Node('td');
$child = new Leaf('Text:', 'Value');
$parent->add($child);
$parent->print();
打印要求:
sometimes <td>Text: Value</td>
sometimes <td>Text:</td><td>Value</td>
到目前为止,我构建了3个解决方案,但没有人满意我,我想知道哪个是更多的OO?还有第四种选择吗?
-- Solution 1 --
// Divide the leaf object to two leaf objects
$leafText = new Leaf('Text: ');
$leafvalue = new Leaf('Value');
$parent->add($leafText);
$parent->add($leafValue);
$parent->print();
-- Solution 2 --
// Change leaf print() logic, if leaf's parent is TD, output "Text: Value",
// otherwise output "<td>Text:</td><td>Value</td>"
-- Solution 3 --
// Change parent add() logic, give leaf a variable $separate to describe if it
// should be divided
function add($child) {
if($child->separate) {
$this->parent->add($child->text);
$this->children[] = $child->value;
}
...
}
答案 0 :(得分:1)
大多数OO都是从数据模型中分离渲染逻辑......控制器应该可以遍历模型层次结构,将数据渲染到视图层次结构中......
另外,“控制链”应该遵循你的层次结构...它不取决于根据父级确定其行为的叶子,由父级从叶子获取信息,然后根据它来处理它自己的状态,或者在查询任何类型的信息时将必要的数据传递给孩子......这样叶子与节点分离......否则你有双向依赖性,这大大降低了可重用性...... / p>
格尔茨
back2dos
答案 1 :(得分:0)
我必须亲自使用解决方案2。你说使用那个解决方案,一个叶子可以容纳一个你不喜欢的节点,但是有什么理由 能够容纳一个节点吗?由于您使用的是不同的类(Node和Leaf),因此您应该能够添加一个阻止将Node传递给Leaf的检查(类似这样):
class Leaf {
public function __construct($text, $value) {
if (is_object($text))
throw new Exception('error message');
if (get_class($value) == 'Node')
throw new Exception('error message');
}
}
这两个检查都应该有效,第二个检查是检查特定的类,而第一个只是阻止所有对象。您也可以使用is_string()
函数,但这将禁止整数。