如何在备忘录模式在C#4实施? [英] How is the Memento Pattern implemented in C#4?

查看:118
本文介绍了如何在备忘录模式在C#4实施?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助备忘录模式本身似乎相当直截了当。我正在考虑实施一样的维基百科的例子,但在此之前我在那里,使得它更容易实现或使用C#的语言功能?


解决方案

一个明显的特征是仿制药,实现一个通用的纪念品将允许你使用它的任何你想要的对象。



许多例子,你会看到将使用一个字符串(包括当前的答复这个问题在所有这些信息)作为状态,这是一个问题,因为它是为数不多的类型之一在.NET这是的一成不变的。



在与处理的可变的对象(如一个二传手属性任何引用类型),你要记住,虽然,当你保存的纪念品,你需要创建对象的deepcopy的。否则,当你改变你原来的对象,你会改变你的纪念品。



您可以通过使用一个串行如 protobuf网这样做 json.net ,因为它们不要求您以纪念像正常的.NET序列化机制序列化的属性,你的对象。确实



CodeProject上有关于通用留念实现几篇文章,但他们往往会忽略deepcopy的部分:



在C#中 <通用备忘录模式进行撤消,重做/ p>

纪念品设计模式


The Memento Pattern itself seems pretty straight forward. I'm considering implementing the same as the wikipedia example, but before I do are there any language features of C# that make it easier to implement or use?

解决方案

One obvious feature would be generics, implementing an generic memento will allow you to use it for any object you want.

Many examples that you will see will use a string (including all those currently among the replies to this question) as state which is a problem since it's one of the few types in .NET which are immutable.

When dealing with mutable objects (like any reference type with a setter-property) you have to remember though that when you save the memento you need to create a deepcopy of the object. Otherwise whenever you change your original object you will change your memento.

You could do this by using a serializer like protobuf-net or json.net since they don't require you to mark your objects with serializable attribute like the normal .net serialization mechanism does.

Codeproject have few articles about generic memento implementations, but they tend to skip the deepcopy part:

Generic Memento Pattern for Undo-Redo in C#

Memento Design Pattern

这篇关于如何在备忘录模式在C#4实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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