dongyong6332 2014-01-03 11:56
浏览 167
已采纳

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

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 2014-01-03 11:59
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试