使用父对象构造子类是一种不好的做法吗?
我有一个搜索类,用于从两个不同的来源获取结果并将它们组合在一起。 Search 类是父类,有两个子类 A 和 B,它们扩展了 Search。
在 Search 类中,我有一个名为 fetch() 的方法,它实例化两个子对象以获取它们的结果。 它看起来像这样:
public function fetch(){
$a = new A($this);
$a_results = $a->fetch();
$b = new B($this);
$b_results = $b->fetch();
// code to combine the results here
}
A 类和 B 类的构造函数都看起来像这样:
class A extends Search
{
public function __construct(Search $search){
parent::__construct($search->category, $search->offset, $search->keywords...);
}
感觉我做错了什么,因为我将父对象传递给子对象,然后使用完全相同的数据创建另一个父对象。 有更好的方法来设置这个吗?
我这样设置是因为我的应用程序的某些部分需要直接访问类 A 和 B,而不是通过父 Search 类。
I have a search class that I am using to fetch results from two different sources and combine them together. The Search class is the parent and has two children A and B which extend Search.
In the Search class, I have a method called fetch() which instantiates the two child objects to get their results. It looks something like this:
public function fetch(){
$a = new A($this);
$a_results = $a->fetch();
$b = new B($this);
$b_results = $b->fetch();
// code to combine the results here
}
The constructor of class A and B both look like this:
class A extends Search
{
public function __construct(Search $search){
parent::__construct($search->category, $search->offset, $search->keywords...);
}
It feels like I'm doing something wrong in that I'm passing a parent object to a child and then creating another parent object with the exact same data. Is there a better way to set this up?
I have it set this way because some parts of my application need to access class A and B directly, rather than through the parent Search class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用组合,例如让 Search 类拥有一个源数组,其中每个源都是 Source 类的一个实例,您可以在其中定义源的公共内容并传递每个 A 和 B 源的参数。
如果还不清楚的话,这里的想法是让 Source 类从源返回数据并让 Search 类进行搜索。 这有多实用或有效取决于实际来源和搜索方式
Use composition, for example have the Search class to have an array of sources, where each source is an instance of a Source class where you define what's common to a source and pass the parameters for each A and B sources.
The idea here, in case it's not clear, is for the Source class to return the data from the sources and let the Search class do the search. How practical or efficient this is depends on the actual source and way of searching