我应该在构造函数中实例化其他类吗? [英] Should I instantiate other classes in a constructor?

查看:52
本文介绍了我应该在构造函数中实例化其他类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我看到我的一个同事在构造函数中实例化了他的类,所以我开始做同样的事情,就像这样:

Recently, I saw a colleague of mine instantiate his classes in a constructor, so I started doing the same, like this:

class FooBar{
private $model1;
private $model2;
    public function __construct() {
        $this->model1=new Model1();
            $this->model2=new Model2();
    }
}

现在我开始怀疑,是否在需要的地方实例化模型可能会更好?

And now I'm starting to wonder, if maybe instantiating the models everywhere where they are needed may be better?

例如,函数foo() 需要model1,函数bar() 需要model2,但是现在两个模型都被加载了.

E.g., function foo() needs model1 and function bar() needs model2, but now both models are loaded.

那么,问题是:这是实例化其他类的正确方法吗?或者我应该在函数中需要它们时才实例化它们?

推荐答案

嗯,一如既往,没有一刀切的答案.

Well, as always there is no one size fits all answer.

大多数时候FooBar 类聚合 $model1$model2 因为它需要它们来实现它的功能.在这种情况下,除非 FooBar 在这些变量中有对象,否则它无能为力,因此在构造函数中创建它们是正确的做法.

Most of the time, class FooBar aggregates $model1 and $model2 because it needs them to fulfill its function. In this scenario there's not much that FooBar can do unless it has objects in these variables, so it's the right thing to do to create them in the constructor.

有时不需要聚合对象来执行类FooBar的大部分功能,并且该对象的构造是一项昂贵的操作.在这种情况下,仅使用如下代码按需构建它是有意义的:

Sometimes an aggregate object is not needed to perform a large part of class FooBar's function, and the construction of that object is an expensive operation. In this case, it makes sense to only construct it on demand with code like the following:

class FooBar {
    private $model1;
    private $model2;

    public function Frob() {
        $model = $this->getModel1();
        $model->frob();
    }

    private function getModel1() {
        if ($this->model1 === null) {
            $this->model1 = new Model1;
        }

        return $this->model1;
    }
}

然而,这只是有时.如果 FooBar 类的一半操作需要 $model1,另一半需要 $model2,这可能表明 FooBar 遇到了让我们把所有东西都放在一个类中"的情况,应该将其拆分为两个类.

However, that's only sometimes. If class FooBar needs $model1 for half of its operations and $model2 for the other half, this may indicate that FooBar is suffering from a case of "let's throw everything inside one class" and should be split into two classes instead.

这篇关于我应该在构造函数中实例化其他类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆