.NET 上的 Memento 实现
我在 .NET 上见过两种不同的 memento 实现。
一个非常简单 - 对象创建其自身的另一个实例。
另一种是使用 BinaryFormatter 和 MemoryStream 序列化对象。
哪种方法是首选方法? 谁能指出每种方法的优点/缺点?
顺便说一句,我有兴趣从资源使用/开发人员生产力的角度来看待它。 我很抱歉没有首先说明这一点。
假设纪念品不需要持久化,哪个更好?
从开发人员生产力的角度来看,序列化毫无疑问胜出。 对于任何对象通用的几行比必须手动创建可能涉及私有构造函数、字段分配等的克隆更有效。
但话又说回来,也许序列化很重 - 我不确定。
I've seen two different implementation of memento on .NET.
One is pretty straightforward - The object creates another instance of itself.
The other is serializing the object using BinaryFormatter and MemoryStream.
Which is the preferred method? Can anyone point out advantages/disadvantages of each approach?
By the way, I am interested in looking at it from resource usage/developer productivity perspective. I apologize for not stating that first.
Assuming that the memento does not need to be persisted, which is preferred?
From a developer productivity point of view, serialization wins hands down. A few lines that are generic for any object is more efficient than having to manually create a clone that involves possibly private constructors, field assignments, etc.
But then again, perhaps serialization is heavy - I'm not certain.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为选择如何创建/存储备忘录取决于您希望备忘录保留多长时间以及是否需要跨应用程序域传达该备忘录。 如果备忘录仅存在很短的时间并且仅由同一线程使用,那么克隆对象是合理的。 如果需要保留备忘录或将其传递到另一个应用程序域,则首选序列化。 如果纪念品寿命很长,您甚至可能想要将其序列化并将其存储在外部(在文件或数据库中)。
I think that the choice of how to create/store the memento depends on how long you want the memento to persist and whether you need to communicate that memento across appdomains. If the memento exists only for a short time and is only used by the same thread, then a cloned object is reasonable. If the memento needs to be persisted or passed off to another appdomain, then serialization would be preferred. If the memento is long lived you may even want to serialize it and store it externally (in a file or DB).
如果您要保留备忘录,请使用序列化方法,
否则,克隆对象就可以了
if you are going to persist the memento, use the serialization method
otherwise, a cloned object is fine
你可以说我疯狂又低效,但我是用 StringBuilder 和字符串来完成我的工作的。
Call me crazy and inefficient but I do mine to a StringBuilder and from a string.
通常,BinaryFormatter 和 MemoryStream 无需编写大量代码即可工作,但 Clone() 需要将代码添加到每个类中。
否则,如果不需要保留备忘录,我看不到在两种方法之间进行选择的匹配项
Often BinaryFormatter and MemoryStream will work without having to write lots of code, but Clone() needs code added to each class.
Otherwise I don’t see match to choose between the two methods if the memento does not need to be persisted