当不在工厂设计中时,一个对象生成另一个对象是否干净?
假设您有一个 ZipFile 类和一个 Content 类。
ZipFile 有一个 load() 方法,用于读取 zip 存档中所有文件的内容并将其放入 Content 对象中。
什么是最合适的OOP设计?
1) ZipFile.load() 将创建一个 Content 对象
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) 为 ZipFile 构造函数提供一个要填充的 Content 对象
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();
基本上,分离对象(松散耦合)更好吗? 作为一名老派的过程程序员,我无法停止质疑设计 OOP 的几种方法。我在“OOP 的最佳方式是什么”上浪费了很多时间。有什么建议可以考虑一下吗?预订?网站?
感谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两种情况的概括是不同的:
第一种情况概括为
ZipFile
了解其内容的具体类,并返回接口的某些实现。第二种情况概括为
ZipFile
了解其内容的接口,并接收一个具体的类(稍后初始化??)。换句话说,第一种情况将
ZipFile
与具体内容类结合起来。第二个将 ZipFile 的客户端和具体的内容类结合起来。鉴于
ZipFile
很可能与其内容一起使用特定的具体类,因此第一个概括可能是更自然的。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 ofZipFile
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.