作为一个软件开发人员,我想为我的客户提供一个扩展库。不应更改库提供商的原始库。
有几种方法可以做到这一点。除了继承,特征也会在脑海中出现。
假设在原始库中有一个类定义为:
class Super {}第一种方法:使用特征扩展原始库:
trait MyTrait {
public function func() {
echo "func in MyTrait\n";
}
}
// Customer writes in his code:
class Sub1 extends Super {
use MyTrait;
}
$sub1 = new Sub1;
$sub1->func();第二种方法:使用继承扩展原始库:
class LibExtension extends Super {
public function func() {
echo "func in LibExtension\n";
}
}
// Customer writes in his code:
class Sub2 extends LibExtension {
}
$sub2 = new Sub2;
$sub2->func();在这种情况下,使用特征与继承相比有什么优势?在哪种情况下,哪种方法更受限制?作为软件开发人员和客户,哪一个给了我更大的灵活性?
如果我们在开放源码或封闭源码领域,这些方法有什么不同吗?
对于这种情况,有没有更好的方法?
发布于 2015-10-12 18:15:39
推荐一种方法比推荐另一种方法非常困难,但在许多情况下,组合是为最终用户提供灵活性的更合适的方式。
考虑到你的特征样本:
trait MyTrait {
public function func() {
echo "func in MyTrait\n";
}
}
// Customer writes in his code:
class Sub1 extends Super {
use MyTrait;
}
$sub1 = new Sub1;
$sub1->func();它可以这样重写:
interface FuncPrinterInterface
{
public function funcPrint();
}
class FuncPrinter implements FuncPrinterInterface
{
public function funcPrint()
{
echo "func in MyTrait\n";
}
}
class UserClass
{
/**
* @var FuncPrinterInterface
*/
protected $printer;
/**
* Sub1 constructor.
*
* @param FuncPrinterInterface $printer
*/
public function __construct(FuncPrinterInterface $printer)
{
$this->printer = $printer;
}
public function doSomething()
{
$this->printer->funcPrint();
}
}
$sub1 = new UserClass(new FuncPrinter());
$sub1->doSomething();https://stackoverflow.com/questions/33064993
复制相似问题