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.
Object.MemberwiseClone Method makes a shallow copy of the object following some very simple rules and taking advantage of how the .NET garbage collector works.
object
.The part about the value types can easily be duplicated with Delphi. Duplicating the reference-type behavior with Delphi, while technically easy, will not provide the expected result: Delphi code is expected to .free
the objects it creates, and it uses a owner-owned
paradigm to make sure that happens. The usual pattern is to free objects created by the owner-object from the destructor. If you make a shalow-copy of the object, this results in failure. Here's an example:
A.Free;
B.Free;
- this automatically calls B.Free
, but unfortunately B was already freed when we freed A!We could attempt a deep-copy
, as David suggests, but that poses some equally difficult problems:
Application
?Putting this all together we can only reach one conclusion: We can't have a general purpose, Delphi equivalent of MemberwiseClone
. We can have a partial look-alike for simpler objects with uncomplicated interactions, but that's not nearly as appealing!
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:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With