德尔福原型图 [英] delphi prototype pattern

查看:130
本文介绍了德尔福原型图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,Delphi的RTTI中是否有任何与MemberwiseClone在C#中一样的原型模式的简单实现。
我看到这个模式的一些Delphi实现,其中正在创建一个新对象(TMyObject.Create),它的属性分配了原型对象的值。我可能是错的,但是如果我们以相同的基本方式创建对象,我看不到模式的好处。



谢谢。

解决方案

没有内置的内容会为您执行深层克隆。我相信你可以根据新的RTTI编写一个深层次的克隆,但我希望它是一个非常平凡的工作量。



如果你正在处理简单的类型,它会工作正常,但你可以很容易遇到严重的挑战。例如,我的头顶部:




  • 某些对象组需要以特定的顺序创建。

  • 不应该克隆某个类的某些成员,例如参考计数。您如何识别RTTI的用户?

  • 您如何处理单身人士?

  • 需要设置的任何外部参考?假设您复制了通常由工厂创建的对象。如果该工厂对其创建的对象提供参考,那么在后面可能会破坏您的设计。



您可以实现您的原型图通过定义一个基本的 Clone()方法,它使用RTTI作为简单类型,然后你必须重写它来更复杂。但是,我个人来自 TPersistent ,并根据使我的克隆()分配


I was wondering, is there anything in the RTTI of Delphi that will do the same as MemberwiseClone does in C# for the simple implementation of the prototype pattern. I saw some Delphi implementations of this pattern where a new object is being created (TMyObject.Create) and it's properties assigned with values from the prototyping object. I might be wrong, but I don't see the benefit of the pattern if we the objects are created in that same basic manner.

Thank you.

解决方案

There's nothing built in that will perform a deep-clone for you. I'm sure you could write a deep-clone based on the new RTTI, but I'd expect it to be a non-trivial amount of work.

If you were dealing with simple enough types it would work fine, but you could easily run into serious challenges. For example, off the top of my head:

  • Some groups of objects need to be created in a specific order.
  • Some members of a class should not be cloned, e.g. reference counts. How do you recognise those with RTTI?
  • How do you deal with singletons?
  • What about any extrinsic references that need to be set up? Suppose you clone an object that is normally created by a factory. If that factory holds a reference to the objects it creates then going behind its back may break your design.

You could implement your prototype pattern by defining a basic Clone() method which uses RTTI for simple types and then you have to override it for anything more complex. Personally though, I'd inherit from TPersistent and make my Clone() method based on Assign.

这篇关于德尔福原型图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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