2014-01-03 11:56
浏览 101


Sometimes when I look at code other people have written I see something like the following:


namespace sys\database;

class Statistics {

    public function __construct() {
        // Database statistics are gathered here using
        // private methods of the class and then set to
        // class properties

    public static function getInstance() {
        return new \sys\database\Statistics();

    // ...


So the static function getInstance() simply returns an object of the class it belongs to. Then, somewhere else in the code I come across this:

$stats = \sys\database\Statistics::getInstance();

Which simply sets $stats to an instance of the Statistics object, ready for its class properties to be accessed to get various database statistics.

I was wondering why it was done this way as opposed to just using $stats = new \sys\database\Statistics();. At the end of the day, all the logic to gather statistics is in the constructor and the getInstance() method doesn't do anything other than returning a new object.

Is there something I'm missing here?

图片转代码服务由CSDN问答提供 功能建议

有时当我查看其他人编写的代码时,我会看到如下内容: \ n

namespace sys \ database; 
class Statistics {
 public function __construct(){
 // //数据库统计信息使用
 // private收集 类的方法,然后设置为
返回new \ sys \ database \ Statistics(); 
 //  ... 

因此静态函数 getInstance()只返回它所属的类的对象。 然后,在我遇到的代码中的其他地方:

  $ stats = \ sys \ database \ Statistics :: getInstance(); 

只需将 $ stats 设置为 Statistics 对象的实例,就可以访问其类属性以获取各种数据库统计信息。< / p>

我想知道它为什么这样做而不是仅仅使用 $ stats = new \ sys \ database \ Statistics(); 。 在一天结束时,收集统计信息的所有逻辑都在构造函数中,并且 getInstance()方法除了返回新对象之外不会执行任何操作。


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doubu1964 2014-01-03 11:59

    This is supposed to be an implementation of the Singleton pattern:

    The pattern is used to never allow more than one instance of the class to be created.

    However, there are a couple of flaws with the implementation you provided: the constructor should be private, and there should be a single private static instance of the class, returned every time the getInstance method is called.

    点赞 评论
  • dongnanke4106 2014-01-03 12:00

    That's a [bad] implementation of the Singleton pattern.

    As a rule of thumb, you should avoid such pattern in favour of more convenient Dependency Injection, for instance.

    点赞 评论
  • douwen8424 2014-01-03 12:01

    This is supposed to be an implementation of the Singleton pattern, which is a term used to describe a class which can only exist once for run-time.

    It seems the implementation you have is flawed however because:

    1. there is no check to see if the class exists yet and
    2. code can create multiple instances by calling the constructor directly (it should be made private)
    点赞 评论

相关推荐 更多相似问题