mardi 28 avril 2015

Why use "getObject" method when writing a Factory class?

Typically a Factory class contains a method like getObject.

Thereby

class Factory
{
    private $type;

    function __construct($type)
    {
        $this->type = $type;
    }

    function getObject()
    {
        //example for brevity only to show use of $type variable
        if ($this->type) $object = new $type();
        return $object;
    }
}

Question: Why not return object straight via constructor?

class Factory
{
    function __construct($type)
    {
        if ($type) $object = new $type();
        return $object;
    }

}

Aucun commentaire:

Enregistrer un commentaire