delphi prototype pattern

前端 未结 5 533
梦毁少年i
梦毁少年i 2021-01-03 05:30

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 so

5条回答
  •  攒了一身酷
    2021-01-03 06:09

    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.

提交回复
热议问题