Memento模式与此代码 [英] Memento pattern vs this code

查看:58
本文介绍了Memento模式与此代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求在采访中解释纪念品模式。我做了类似的事情。

这段代码看起来像Memento模式吗?它有什么不同?



I was asked to explain memento pattern in an interview. I did something like this.
Does this code look like Memento pattern? Where is it different?

namespace ConsoleApplication1
{
    class Originator:ICloneable
    {
        public string a;
        public int b;

        public object Clone()
        {
            Originator o = new Originator();
            o.a = this.a;
            o.b = this.b;
            return o;
        }
    }

    class CareTaker
    {
        List<Originator> l = new List<Originator>();

        public void SaveMemento(Originator o)
        {
             l.Add((Originator)o.Clone());
        }

        public Originator RetrieveMemento(int i)
        {
            return l[i];
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CareTaker c = new CareTaker();
            Originator o = new Originator();
            c.SaveMemento(o);

        }   
    }
}

推荐答案

如果有人要求解释 那么设计模式就没有必要编写任何代码了 - 你最好用语言来设计模式试图实现什么,并且可以添加一个UML图。



如果没有,你可以在你的代码中添加一些注释来证明你对模式的了解。



你的主要功能实际上应该显示状态的变化然后回滚到上一个状态以完全展示模式。



看看这个例子进行比较http://www.dofactory.com/Patterns/PatternMemento.aspx [ ^ ]
If you were asked to "explain" the design pattern then there was no need to write any code - you''d have been better off putting in words what the design pattern tries to achieve and possible adding a UML diagram.

Failing that you could have put some comments in your code to demonstrate your knowledge of the pattern.

Your Main function should actually show a change of state and then roll-back to the previous state to fully demonstrate the pattern.

Have a look at this example for comparison http://www.dofactory.com/Patterns/PatternMemento.aspx[^]


这篇关于Memento模式与此代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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