我可以使用什么设计模式来模拟 PHP 中的特征/混合?
由于 Trait 在 PHP 5.3 中不可用,据我所知,我需要模拟它们提供的一些功能。接口不起作用,因为我需要具体的功能。
问题:
我有两个客户端类需要共享一些功能,但从不同的基类扩展。
ClassA extends Foo {}
ClassB extends Bar {}
我需要能够在两个类中实现一个名为 getComponent() 的函数,并且它需要具有相同的功能。
更改基类不是一个选项。我正在考虑做这样的事情:
Class ComponentHandler {
function getInstance() {
//return singleton
}
function getComponent() {
//required functionality
}
}
Class A extends Foo {
var $handler;
function __construct() {
$this->handler = ComponentHandler::getInstance();
}
}
我将在 ClassA 和 ClassB 中实现这个构造函数。在我的客户端中,我会拨打这样的电话:
$class = new ClassA();
$class->handler->getComponent();
$class = new ClassB();
$class->handler->getComponent();
Since traits aren't available in PHP 5.3 AFAIK I need to emulate some of the functionality they offer. Interfaces won't work because I need concrete functionality.
Problem:
I have two client classes that need to share some functionality but extend from different base classes.
ClassA extends Foo {}
ClassB extends Bar {}
I need to be able to implement a function called getComponent() in both classes and it needs to be functionality identical.
Changing the base class is not an option. I was thinking to do something like this:
Class ComponentHandler {
function getInstance() {
//return singleton
}
function getComponent() {
//required functionality
}
}
Class A extends Foo {
var $handler;
function __construct() {
$this->handler = ComponentHandler::getInstance();
}
}
I would implement this constructor in both ClassA and ClassB. In my client I would make calls like this:
$class = new ClassA();
$class->handler->getComponent();
$class = new ClassB();
$class->handler->getComponent();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我更喜欢尽可能通过构造函数传递对象。您的方法依赖于类名
ComponentHandler
。通过构造函数传递对象并添加 类型提示 您仍然在添加依赖项,但是一个允许您创建不同类型的 ComponentHandler 类的类可以采用任何扩展 ComponentHandler 的处理程序,这也可以工作...
I prefer to pass objects via the constructor whenever possible. Your method has a dependency on the Class Name
ComponentHandler
. By passing the object via the constructor and adding a type hint you are still adding a dependency, but one that allows you to create different type ofComponentHandler
sClass can take any handler that extends ComponentHandler, this will work too...