Matlab OOP调用get方法保存瞬态属性。

时间:2011-07-28 21:59:06

标签: oop matlab save transient

我正在尝试实现一个具有可能提供给构造函数的属性的类,或者可能在其他方法中生成的类。我不希望将数据保存到磁盘或在加载时生成。到目前为止我所拥有的是:

classdef MyClass
        properties(GetAccess = public, SetAccess = private)
            Property1
            Property2
            Property3
        end
        properties(Access = private)
            Property4
        end
        properties(Transient = true)
            ProblemProperty
        end
        properties(Dependent = true, Transient = true)
            Property5
        end

        methods
            function MyClass
                % Constructor.
            end

            function val = get.Property5(B)
                val = SomeFunction(Property1);
            end

            function val = get.ProblemProperty(B)
                if isempty(B.ProblemProperty)
                    B = GenerateProblemProperty(B);
                end
                val = B.ProblemProperty;
            end

            function B = GenerateProblemProperty(B)
                B.ProblemProperty = AnotherFunction(B.Property2);
            end
        end
    end

问题在于,当我尝试将对象保存到磁盘时,Matlab会调用get.ProblemProperty方法(通过在save语句上运行探查器来确认)。 ProblemProperty字段为空,我希望它保持这种状态。它不会调用get.Property5方法。

如何避免调用get.ProblemProperty?

2 个答案:

答案 0 :(得分:1)

由于有时可以设置属性(即在构造函数中),因此该属性不是严格依赖的。一种解决方案是将可设置值存储在构造函数中的私有属性(以下示例中为CustomProblemProperty)中。 get ProblemProperty方法会检查返回此私有属性值,如果它不为空,否则返回生成的值。

classdef MyClass
    properties(GetAccess = public, SetAccess = private)
        Property1
        Property2
        Property3
    end
    properties(Access = private)
        Property4
        CustomProblemProperty
    end
    properties(Dependent = true, Transient = true)
        ProblemProperty
        Property5
    end

    methods
        function B = MyClass(varargin)
            if nargin == 1
               B.CustomProblemProperty = varargin{1};
            end
        end

        function val = get.Property5(B)
            val = SomeFunction(Property1);
        end

        function val = get.ProblemProperty(B)
            if isempty(B.CustomProblemProperty)
               val = AnotherFunction(B.Property2);
            else
               val = B.CustomProblemProperty;
            end
        end

    end
end

答案 1 :(得分:1)

你的解决方案正在发挥作用,但它不是OOP精神,你混合的是存取物,它是物体的外部形状和内部物体。

我会建议以下

classdef simpleClass
    properties(Access = private)
        % The concrete container for implementation
        myNiceProperty % m_NiceProperty is another standard name for this.
    end
    properties(Dependent)
        % The accessor which is part of the object "interface"
        NiceProperty
    end

    method
        % The usual accessors (you can do whatever you wish there)
        function value = get.NiceProperty(this)
            value = this.myNiceProperty;
        end
        function set.NiceProperty(this, value)
            this.myNiceProperty = value;
        end
    end
end

然后NiceProperty永远不会保存在任何地方,您可以编写标准代码。

相关问题