Matlab代理类问题。 (re:依赖属性)

时间:2011-03-02 23:05:40

标签: oop class matlab proxy

考虑以下Matlab(2009a)类:

classdef BigDeal < handle
    properties
        hugeness = magic(2000);
    end
    methods
        function self = BigDeal()
        end
    end
end


classdef BigProxy < handle
    properties(Dependent)
        hugeness
    end
    properties(Access = private)
        bigDeal
    end
    methods
        function self = BigProxy(bigDeal)
            self.bigDeal = bigDeal;
        end
        function value = get.hugeness(self)
            value = self.bigDeal.hugeness;
        end
    end
end

现在考虑以下用途:

设定:

>> b = BigDeal

b = 

  BigDeal handle

  Properties:
    hugeness: [10x10 double]

  Methods, Events, Superclasses

OneLayer:

>> pb = BigProxy(b)

pb = 

  BigProxy handle

  Properties:
    hugeness: [10x10 double]

  Methods, Events, Superclasses

TwoLayers:

>> ppb = BigProxy(pb)

ppb = 

  BigProxy handle with no properties.
  Methods, Events, Superclasses

问题:为什么我的双层代理无法在单层可以看到hugeness?可以计算相关属性 - 但由于某种原因这只会导致一层深度吗?


更新:请参阅下面的答案以获取解决方法。

2 个答案:

答案 0 :(得分:4)

这里的问题有两方面:

  1. BigProxy对象构造函数用于接受具有(非依赖)hugeness属性(如BigDeal对象)的输入对象,{{{1}然后,对象可以访问以计算其自己的依赖BigProxy属性的值。

  2. 在创建hugeness时,您正在将BigProxy对象传递给BigProxy构造函数,并且您显然无法从另一个依赖属性计算依赖属性。例如,这是我尝试访问ppb时抛出的错误:

    ppb.hugeness

    换句话说,外部??? In class 'BigProxy', the get method for Dependent property 'hugeness' attempts to access the stored property value. Dependent properties don't store a value and can't be accessed from their get method. 对象尝试通过访问内部BigProxy对象的存储值hugeness来计算其从属hugeness属性的值,但是没有存储值,因为它是dependent property

  3. 我认为对于这种情况的修复将是BigProxy构造函数检查其输入参数的类型以确保它是BigProxy对象,否则抛出错误。 / p>

答案 1 :(得分:4)

Gnovice为“为什么”这个问题提供了一个很好的答案,因此我授予他荣耀的绿色检查。但是,对于那些想要解决问题的人,你可以这样做:

classdef BigDeal < handle
    properties
        hugeness = magic(10000);
    end
    methods
        function self = BigDeal()
        end
    end
end


classdef BigProxy < handle
    properties(Dependent)
        hugeness
    end
    properties(Access = private)
        bigDeal
    end
    methods
        function self = BigProxy(bigDeal)
            self.bigDeal = bigDeal;
        end
        function value = get.hugeness(self)
            value = self.getHugeness;
        end
    end
    methods(Access = private)
        function value = getHugeness(self)
            if isa(self.bigDeal,'BigProxy')
                value = self.bigDeal.getHugeness;
            else
                value = self.bigDeal.hugeness;
            end
        end
    end
end

允许您执行以下操作

>> b = BigDeal;
>> pb = BigProxy(b);
>> ppb = BigProxy(pb);

{bpbppb}中的每一个都具有相同的公共方法和属性。唯一的缺点是我不得不(不必要地恕我直言)用一个新的私人吸气器弄乱BigProxy。