Can I "cast" a value class object to a handle class object on the fly
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Matt J
2014-11-5
编辑:Matt J
2014-11-5
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.
更多回答(2 个)
Phillip
2014-11-5
2 个评论
Adam
2014-11-5
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
2014-11-5
编辑:Matt J
2014-11-5
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?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!