Can I "cast" a value class object to a handle class object on the fly
16 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi
I'm relatively new to OOP. I currently have a value class object. Specifically, it's a custom date class that I'm working on. So, most of the time it makes sense to have the object as a value class.
However, there are occasions where I would want a particular instance of an object to be viewed as a handle class. Specifically in my case this could happen where I have an object that is let's say the current date. Hence if current date changes, all objects linked to that object should update. This obviously sounds like a handle class object.
So the question is, is there a way that I can use my date value class and cast a specific instance of that object as a handle.
Hope I stated that clearly.
Regards, Phillip
0 Kommentare
Akzeptierte Antwort
Matt J
am 5 Nov. 2014
Bearbeitet: Matt J
am 5 Nov. 2014
I found a way to do it (see the attached classdef file myclass.m), but it's fancy. Basically, it uses a Dependent property called "theDate" as an interface to let you get and set data. However, the data will be sent to or drawn from a value variable or a handle variable, depending on whether the object's "type" property is set to 'handle' or 'value'.
The usage works like this,
obj1=myclass('May 1');
obj2=cast(obj1,'handle');
obj3=obj2;
This creates a value object obj1. The cast() method then creates an unshared copy obj2 of obj1. However, obj2 will now have handle semantics. So, obj2 and obj3 will be linked with each other, but neither will be linked to obj1.
>> obj3.theDate='Jan 9'; obj1, obj2,obj3
May 1
Jan 9
Jan 9
The accompanying test.m runs a more extensive script of tests.
Weitere Antworten (2)
Phillip
am 5 Nov. 2014
2 Kommentare
Adam
am 5 Nov. 2014
This does look useful and not something I have used before. I tend to default to using a handle class most of the time because I prefer them, but certainly they are not always the appropriate solution to a problem and I have had situations before where I wanted deep copies of handle class objects which can get very messy.
Matt J
am 5 Nov. 2014
Bearbeitet: Matt J
am 5 Nov. 2014
You would use a converter method, I think
I don't think you can avoid writing a second class that is a handle version of the original class, if that's what you're asking.
Are you sure it makes sense to have a value class version in the first place? I didn't follow your explanation of that. What if you made it a handle class to begin with and then had a class method unshare() to make unlinked copies when you need them?
1 Kommentar
Siehe auch
Kategorien
Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!