|
"david cottrell" <david.cottrell@gmail.com> wrote in message <hgdk6u$skr$1@fred.mathworks.com>...
> I'm confused as to what is the best way to implement an value object (not handle) that is mutable.
>
> For example, define a simple "experiment" object that has various input and output parameters and methods that perform the experiment (modifying internal output variables) and compute and plot things.
>
> A handle class basically does this but is a handle so creating independent copies is more inolved:
>
> classdef experiment < handle
> ...
> end
>
> Creating a function that returns a structure with handles to all the necessary variables and subroutines will do the trick I think:
No, it won't. Consider the following implementation of your idea
function p = experiment
p.param1=3;
p.method1 = @f;
function f
p.param1=rand(1000,1000);
end
end
>> z=experiment
z =
param1: 3
method1: @experiment/f
>> z.method1()
>> z,
z =
param1: 3
method1: @experiment/f
So you see, z.method1() failed to change z.param1 as was your intention.
The real result of z.method1() is sitting somewhere inside the function handle:
>> T=functions(z.method1); T=T.workspace{1}; T=T.p
T =
param1: [1000x1000 double]
method1: @experiment/f
Another disadvantage of this approach is that, the memory consumption of z attributed to the function handle z.method1 is invisible, as you can see from the following,
>> whos z T
Name Size Bytes Class Attributes
T 1x1 8000388 struct
z 1x1 272 struct
Still, it can be a useful quick and dirty way of obtaining oop features at times. I use it occasionally.
|