管理具有属性的多个Windows

时间:2017-01-12 23:12:56

标签: vb.net visual-studio

我正在构建一个具有多个表单的应用程序,每个表单都有自己的公共属性。我创建了它们的多个实例,并在用户关闭它时隐藏表单,只是为了在内存中维护它的属性值。我不想将属性移动到更一致的地方,因为有很多不同的形式,经常访问,我试图保持井井有条。我也不想隐藏所有可能未使用的表单来存储这些属性值。处理这种情况的最佳方法是什么?

我希望你能理解我的意思而不显示任何代码。如果你认为它会有所帮助,我会很高兴,但我想在这里成为一般人。我认为这更像是一个方法论问题。

1 个答案:

答案 0 :(得分:0)

这样做的好方法之一是使用Memento模式。例如,在伪代码中:

假设您有一个包含属性的表单。表格当然是记忆沉重的,你想要“记住”你的财产,而不是形式

' declare memento interface
Interface IForm1Memento
    ' declare properties here
    . . . . . 
    Sub SetMemento()
    Sub GetMemento()
 End interface    

 ' inherit in form
 public class form form1
     inherits IForm1Memento
     . . . . 
     Sub SetMemento
          dim m As IForm1Memento = MementoFactory.Get(me)
          ' here you can do property by property or create reflection based hydrator
          ' or use AutoMapper (free product) to fill memento object (see below)
          MementoStorage.Store(key, m) ' this could be a global dictionary or cache like nCache
     end sub

     Sub GetMemento
          dim m As IForm1Memento = MementoStorage.Retrieve(key)
          ' again, here hydrate your form from memento
     end sub

 end class


 ' inherit interface in memento object
 public class Form1Memento
     inherits IForm1Memento
     ' here ho same property implementations as in form1
 end class

现在,如果您还使用xml属性装饰Form1Memento,则可以将其存储在文件系统中并在下次应用启动时检索它。或者,如果您愿意,可以使用JSON。

那么,我们有什么结果呢? - 表格可以去,关闭和加载。事实上,您可以在form.load上加载纪念品并保存在form.closed上。您可以将您的纪念品保存在文件系统上或存储在内存中 - 缓存,字典,列表等。