什么时候使用单例? [英] When to use a singleton?

查看:154
本文介绍了什么时候使用单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

class MyController {
public function newUserAction()
{
    $view = new View('myfrontend');
    if($this->request->isPost())
    {
        $form = new MyForm;
        $posts = $this->request->getPosts();
        if($form->isValid($posts))
        {
            //...
        }
    }
    $view->display();
}

}

所以,每当表单没有正确填充,该过程再次开始,所以每次有一个新视图('myfrontend')等。但是这是一件好事吗?一次又一次有一个新的视图对象。

So, everytime the form is not filled in correctly, the process starts again and so every time there is a "new View('myfrontend')" ect. But is that a good thing? To have a new view object again and again and again.

这里不是更好的单例工作吗?

Ain't it better to work with singletons here?

推荐答案

从来没有。很简单。



当您再次显示一个无效的表单时,它必须重新提交。这将是一个全新的请求。应用程序将通过完整的引导和分派。单例在这里不会有帮助,因为PHP中的单例只会为请求生存。

Never ever. Simple as that.

When you display an invalid form again, it has to be resubmitted anyway. That will be an entirely new Request. The application will go through through the full bootstrap and dispatch. A singleton would not help here, because Singletons in PHP will also only live for the Request.

此外,单身人士更难测试。我还没有遇到一个UseCase,当使用依赖注入。即使 Erich Gamma (Singleton模式的发明者之一)也怀疑这种模式:

In addition, Singletons are much more difficult to test. I have yet to come across a UseCase where a Singleton can not be avoided when using Dependency Injection. Even Erich Gamma, one of the Singleton pattern's inventors, doubts this pattern nowadays:


我赞成丢弃Singleton,它的使用几乎总是一种设计气味

你最好避免单身。

这篇关于什么时候使用单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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