1

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

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 方法(通过仅在保存语句上运行分析器来确认)。ProblemProperty 字段为空,我希望它保持这种状态。它不调用 get.Property5 方法。

如何避免调用 get.ProblemProperty?

4

2 回答 2

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
于 2011-07-28T22:15:42.427 回答
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 永远不会保存在任何地方,您可以从编写标准代码中受益。

于 2012-01-04T09:59:33.170 回答