在我的应用程序子类的构造我有一个数字,呈现不同的元素。我创建了一个抽象类,在其中扩展。用不同数量的参数
abstract class Element {
protected $_value = null;
public function __construct($value) {
$this->_value = $value;
}
// ...
public abstract function render();
}
一个元素的例子可能是一些文字包裹在段落标记中。
class TextElement extends Element {
public function render() {
return "<p>{$this->_value}</p>\n";
}
}
我无法创建具有多个值的元素。例如,图像元素可能会呈现图像标记并包含多个属性。这是一个问题,因为抽象类中的构造函数只接受一个参数。我看到了解决这个问题的两种可能的解我能通过在含有不同的属性的元素构造(溶液1)的阵列或I可以覆盖在子类的构造(溶液2)。我的问题是,这些解决方案中的哪一个是更好的设计,还是它们存在更好的解决方案?我应该使用接口吗?
解决方案1
class ImageElement extends Element {
public function render() {
return "<img src=\"{$this->_value['src']}\" alt=\"{$this->_value['alt']}\" />";
}
}
$imageElement = new ImageElement(array('src' => '/image.png', 'alt' => 'image'));
解决方案2
class ImageElement extends Element {
protected $_alt;
public function __construct($src, $alt) {
$this->_value = $src;
$this->_alt = $alt;
}
// ...
public function render() {
return "<img src=\"{$this->_value}\" alt=\"{$this->_alt}\" />";
}
}
如果我要使用一个接口,我将失去循环通过元素集合的能力。使用接口和抽象类是否可行?我看到的唯一问题是抽象类基本上是空的。 – birderic 2011-05-09 16:43:44