mardi 28 janvier 2020

Is there a name for this 'pattern'?

I recently encountered a situation where it was useful to create a lazy-loading version of a class by wrapping its factory.

I'd like to do some research to find out if there are any issues I hadn't thought of before I rely too heavily on it, but I don't know what to look for.

edit: In my case it involves creation of cookies and session files, which I don't want to do until a user's credentials are verified.

interface FooInterface
{
    public function bar();
}

class Foo implements FooInterface
{
    public function bar()
    {
        ...
    }
}

interface FooFactoryInterface
{
    public function getFoo():FooInterface;
}

class FooFactory
{
    public function getFoo():FooInterface
    {
        return new Foo(...);
    }
}

class LazyFoo implements FooInterface
{
    protected
        $foo=null,
        $factory;
    public function __construct(FooFactoryInterface $factory)
    {
        $this->factory=$factory;
    }
    public function bar()
    {
        if($this->foo===null) $this->foo=$this->factory->getFoo();
        return $this->foo->bar();
    }
}

Aucun commentaire:

Enregistrer un commentaire