开发者

Is it clean for an object to generate another object when not in a factory design?

Say you a class ZipFile and a class Content.

ZipFile has a load() method for reading the contents of all files in the zip archive and put it in a Content object.

What is the most appropriate OOP design ?

1) ZipFile.load() will create a Content object

class ZipFile
{
    public function load()
    {
        // Load all files in zip
        // ...
        Content content = new Content();
        content->set(data);
        return( content );
    }
}
ZipFile zf = new ZipFile();
Content ct = zf->开发者_运维技巧;load();
ct->print();

B) Give the ZipFile constructor a Content object to fill

class ZipFile
{
    private Content content;

    public function ZipFile(content) // constructor
    {
        this->content = content;
    }    
    public function load()
    {
        // Load all files in zip 
        // ...
        this->content->set(data);
    }
}
Content ct = new Content();
ZipFile zf = new ZipFile(ct);
zf->load();
ct->print();

Basically, is it better to separate objects (loose coupling) ? As an old-school procedural programmer I cannot stop questionning the several ways of designing OOP. I lose a lot of time on "what is the best way to OOP this. Any advice to think it through ? Book ? Website ?

Thanks for your help


The generalizations for the two cases is different:

The first case generalizes to ZipFile knowing the concrete class of its contents, and returning some implementation of an interface.

The second case generalizes to ZipFile knowing an interface for its contents, and receiving a concrete class (to initialize later??).

Stated in another way, the first case couples ZipFile and whatever the concrete content class is. The second couples the client of ZipFile and the concrete content class.

Given that it is quite likely that ZipFile goes with a specific concrete class for its contents, the first generalization is probably the more natural one.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜