[plt-scheme] OOP problem - cloning objects
On Saturday, September 21, 2002, at 08:08 AM, Erich Rast wrote:
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
> Hi,
>
> I've stumbled over an oop problem that probably has an easy standard
> solution but right now I'm confused. I have several subclasses of
> MrEd's text% class, like e.g. text% > z-text% > z-entry%.
>
> Now I need to create a deep copy of instances of such classes.
> Therefore, I have created an interface clonable-object<%> with a
> method clone that is supposed to return a deep copy of the resp.
> object.
>
> Problem: Each superclass sure knows how to clone itself, but naturally
> it can only return an instance of its own class in its clone method.
> It would seem natural for z-entry% to rename the clone method of
> z-text%, calling the superclass method, cloning any information that
> is new to z-entry%, and return a new instance of z-entry%. But the
> superclasses clone method will return an instance of z-text%.
>
> Does that mean that e.g. z-entry% has to re-implement all of the clone
> code that is already in its superclass z-text%? Is there a simple
> trick I've overseen to clone objects such that each derived class only
> provides "its own part" to the cloning process? Is there some way to
> cast an object into an object of a derived class?
Well, this is a classic extensibility problem. Off the top of my head,
I see two solutions (which are the same, at some level):
1) cloning through mutation: The "clone" method takes an object to be
cloned, and makes the "this" object just like the argument. When
z-entry%'s clone method calls z-text%'s clone method, "this" still
refers to an object of class z-entry%. The drawback of this is that
you have to first create a "blank" element of z-entry%. This may not
always be possible. Which suggests
2) cloning through a "copy constructor": one of the instantiation
fields is an object to be cloned. If the clone argument is provided,
all other arguments are ignored (semi-ick) and the new object becomes a
clone of the old one. Of course, this can't be represented as an
interface.
john clements