开发者

Factory or constructor - where to set object properties?

I am a little bit confused about, what is the right place to set object properties, in constructor or in factory method, or it doe开发者_开发百科s not matter?

In constructor:

class Foo {
    public $bar;
    function __constructor($b) {
        $this->bar = $b;
    }

    static function factory($b) {
        return new self($b);
    }
}

In factory:

class Foo {
    public $bar;    

    static function factory($b) {
        $obj = new self();
        $obj->bar = $b;
        return $obj;
    }
}


The question is can you instantiate the class without setting the b property. If it will work, you do not need to set the property in the constructor. If the property is important for others method to work, you have to set it in the constructor. Factory has nothing to do with this. If the factory was the only way to instantiate the class (the constructor was private), then the code would be encapsulated, but still you need to pass the required parameters to the constructor, otherwise you can easly forget about them when you refactor your code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜