如果一个对象本身写出到一个文件中,还是应该就可以了另一个对象的行为进行I / O? [英] Should an object write itself out to a file, or should another object act on it to perform I/O?

查看:106
本文介绍了如果一个对象本身写出到一个文件中,还是应该就可以了另一个对象的行为进行I / O?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注:很抱歉的长期问题

我试图理解面向对象后面的一些重点领域和我做不到决定我的特定问题或那种方式。

I'm trying to understand some key areas behind object orientation and I couldn't decide one way or another about my particular question.

比方说,我有一个对象充满可爱的数据。 。鲍勃类

Let's say I have an object full of lovely data. Class bob.

Bob myBob = new Bob("This string is data");

比方说,我想myBob的内容保存到一个XML文件(bob.xml)

Let's say I want to save the contents of myBob to an xml file (bob.xml)

我是否应该在鲍勃的对象行为写的内容了,或者我应该myBob要这样做呢?

Should I have an object act on bob to write the contents out, or should I have myBob do this?

案例1:法案对象

Writer myWriter = new Writer(myBob, "C:\\bob.xml");



案例2:保存方法

myBob.Save("C:\\bob.xml");



有些人是偏袒的选择之一,因为它意味着如果写文件的代码被改变,这不是'T需要跨每个保存方法更新;促进代码重用我想。我的这个问题是让所有的数据从可具有无访问私人数据对象的

Some people are siding with option one as it means if the code for writing files is changed, it doesn't need to updated across every Save method; promoting code reuse I suppose. My problem with this is getting all the data out of objects which may have private data with no accessor.

有方案二的情况是,该方法只作用于数据由对象持有,这就是事情应该是这样。其他对象无干扰。

The case for option two is that the method only acts on the data held by the object and that's the way it should be. No interference from other objects.

或者是回答我的问题的那些情况下依赖的问题呢?如果是这样,你怎么知道当一个方法是首选比其他?

Or is the answer to my question one of those "case dependent" issues? If so, how do you know when one method is prefered over the other?

推荐答案

正确的方法,在一般情况下,是你的案例1.这保持了类没有它连接到一个特定的持久性机制(磁盘)的单一责任(无论它)。

The correct approach, in general, is your Case 1. This maintains a single responsibility for the class (whatever it does) without coupling it to a specific persistence mechanism (a disk).

您正在寻找一处更广义的问题具体情况:序列化。这是很好的,并确定一个对象有一些手段来表明它应该如何serialized--那就是知道什么是必要的反序列化,毕竟唯一实体。但是,如果你使对象本身保存到磁盘,你紧耦合的对象到具体实施。

You're looking at a specific case of a more generalized problem: Serialization. It's good and OK for an object to have some means to indicate how it should be serialized-- it's the only entity that knows what's necessary to deserialize it, after all. But if you make the object save itself to disk, you've tightly coupled that object to a specific implementation.

相反,考虑创建一个接口,一个广义的作家可以使用序列化的对象到任何的作家序列化为。这样,你就可以序列化到磁盘,网络,内存,任何你实际上需要序列化。 :)

Instead, consider creating an interface that a generalized "writer" can use to "serialize" the object to whatever that writer serializes to. This way, you'll be able to serialize to disk, to the network, to memory, to whatever you actually need to serialize to. :)

这篇关于如果一个对象本身写出到一个文件中,还是应该就可以了另一个对象的行为进行I / O?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆