dongyong6332
dongyong6332
2014-01-03 11:56

静态方法返回一个类的实例是什么意思?

已采纳

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

<?php

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doubu1964 doubu1964 7年前

    This is supposed to be an implementation of the Singleton pattern: http://www.oodesign.com/singleton-pattern.html

    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.

    点赞 评论 复制链接分享
  • douwen8424 douwen8424 7年前

    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)
    点赞 评论 复制链接分享
  • dongnanke4106 dongnanke4106 7年前

    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.

    点赞 评论 复制链接分享

相关推荐