MATLAB - 在其他属性更改的情况下更新私有属性

时间:2017-11-26 01:41:44

标签: matlab oop properties dependencies private

我有一个具有依赖属性的类,需要一段时间才能进行评估。出于这个原因,我希望不是每次查询时都要对它进行评估,而是仅在对象被实例化并且某些属性被更改时才进行评估。我发现this interesting solution基于定义在必要时设置的额外私有属性,依赖属性获取此额外私有属性的值。

现在的问题是:如何在实例化对象时确保设置此私有属性,并在对象的某些属性发生更改时自动更新?

1 个答案:

答案 0 :(得分:1)

建议的解决方案是完美的,只需确保在类构造函数中为依赖属性定义默认值,并将其代理设置为适合您需要的默认值:

methods
    function this = MyClass(...)
        % default starting values for your properties 
        this.MyProperty1 = 0;
        this.MyProperty2 = -8;
        this.MyProperty3 = 3;

        % calculate the initial value of your dependent
        % property based on the default values of the other
        % properties (this is basically the computeModulus
        % function of your example)
        this.UpdateMyDependent();
    end
end

在修改其他属性时使您的依赖属性更新的逻辑已包含在链接的线程中,在您的类中实现它们。

function this = set.MyProperty1(this,value)
    this.MyProperty1 = value;
    this.UpdateMyDependent();
end

function this = set.MyProperty2(this,value)
    this.MyProperty2 = value;
    this.UpdateMyDependent();
end

function UpdateMyDependent(this)
    this.MyDependentProxy = this.MyProperty1 * this.MyProperty2;
end

function value = get.MyDependent(this)
    value = this.MyDependentProxy;
end