Skip to content
Advertisement

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();
    }
}

Advertisement

Answer

This is known as the proxy pattern, coupled with the abstract factory pattern as the purpose of this particular proxy is to delay the instantiation itself by lazy initialisation. I doubt this combination is common enough to have its own name. Usually the problem is solved by simply delaying the call to the factory method itself, doing the lazy initialization in the code that actually uses the object.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement