【发布时间】:2015-03-10 12:48:16
【问题描述】:
什么时候应该使用单例模式和静态(静态方法和静态属性)?
我读过很多博客/教程/cmets,它们总是说单例模式,所以我从不使用它。
但同样,有很多 php 框架都在使用单例,例如最近越来越流行的 Laravel。
例如,在 Laravel 中,
$app->singleton(
'Illuminate\Contracts\Http\Kernel',
'App\Http\Kernel'
);
$app->singleton(
'Illuminate\Contracts\Console\Kernel',
'App\Console\Kernel'
);
$app->singleton(
'Illuminate\Contracts\Debug\ExceptionHandler',
'App\Exceptions\Handler'
);
如果你检查它,你可以在 Laravel 中大量使用单例(似乎)。那么发生了什么?
据了解,Singleton 是STUPID that we should avoid 中的第一个字母。
但我相信有些程序员会强烈反对——Its the best way to do it in that situation - if you need to use them, use them. Simple as that.
那么,在什么情况,如果你不同意 STUPID,你应该使用单例?
另外,在 Laravel 中,你会看到很多这样的东西,
$users = DB::table('users')->get();
我猜它要么是一个单例,要么是一个静态方法(我对 Laravel 不太擅长——刚刚开始研究它)。
看起来好用,但是在测试中,会不会很难测试?
我在其他框架中也经常看到这种方法 (DB::something(...))。他们似乎不是一个好主意,但我相信很多人也会不同意。那么在什么情况你应该使用静态方法呢?
【问题讨论】:
标签: php design-patterns singleton static-methods