开发者

Clarification on Singleton Pattern

开发者 https://www.devze.com 2023-02-25 17:02 出处:网络
I\'m writing some utility classes for a PHP app and a lot of them will be singletons.Found myself re-writing the same code over开发者_运维知识库 and over, and decided to make an abstract base class Si

I'm writing some utility classes for a PHP app and a lot of them will be singletons. Found myself re-writing the same code over开发者_运维知识库 and over, and decided to make an abstract base class Singleton and subclass it. Just want to make sure I've done this correctly!

abstract class Singleton
{
    private static $instance = NULL;

    public static final function getInstance()
    {
        if(self::$instance == NULL)
            self::$instance = instantiate();

        return self::$instance;
    }

    protected abstract static function instantiate();
}

class LogHelper extends Singleton
{
    protected static final function instantiate()
    {
        return new LogHelper();
    }
}

Now, if I have done this correctly, I can call LogHelper $LOGGER = LogHelper::getInstance() from anywhere in my codebase, and get a reference to the same instance every time, yes?


You will probably need to define your getInstance() methods as static so that you can access them without having to instantiate the class. Then, you'll use this:

$objSingleton = LogHelper::getInstance();

And, you'll probably want to define a private constructor:

private function __construct() { }


While singletons seem like the ideal solution at first, they are not. Learn about registries and dependecy injection; they will make your life easier when you start unit testing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号