我正在尝试决定我正在使用的类结构的设计模式,并且我在实现类的设置的最佳方式上被撕裂。
一种方法在抽象类的构造函数中调用抽象设置函数,另一种方法是覆盖扩展抽象类的类中的构造函数。
一些(人为的和简化的)例子来概述我的想法:
调用抽象方法
<?php
abstract class VehicleAbstract implements VehicleInterface
{
protected $_wheels;
private $_engine;
public function __construct(EngineInterface $engine)
{
$this->setupWheels();
$this->_engine = $engine;
$this->_engine->setWheelsToDrive($this->_wheels);
}
public abstract function setupWheels();
}
class Car extends VehicleAbstract
{
public function setupWheels()
{
$this->_wheels = array(
"frontL",
"frontR",
"backL",
"backR"
);
}
}
优点:
缺点:
覆盖构造函数
<?php
abstract class VehicleAbstract implements VehicleInterface
{
protected $_wheels;
private $_engine;
public function __construct(EngineInterface $engine)
{
$this->_engine = $engine;
$this->_engine->setWheelsToDrive($this->_wheels);
}
}
class Car extends VehicleAbstract
{
public function __construct(EngineInterface $engine)
{
$this->_wheels = array(
"frontL",
"frontR",
"backL",
"backR"
);
parent::__construct($engine);
}
}
优点:
缺点: