Can I "cast" a value class object to a handle class object on the fly
조회 수: 14 (최근 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에서 Class File Organization에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!