2011-07-28 33 views
1

我想實現一個可以提供給構造函數或可能在其他方法中生成的屬性的類。我不想將數據保存到磁盤或在加載時生成。我至今是:Matlab OOP調用get方法保存瞬態屬性。

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?

回答

1

由於有時可以設置屬性(即在構造函數中),那麼這個屬性不是嚴格依賴的。一種解決方案是將可設置的值存儲在構造函數中的私有屬性(下例中的CustomProblemProperty)中。如果ProblemPropertyget方法不爲空,則將檢查返回此私有屬性值,否則返回生成的值。

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 
+0

我想過這個,但有時候這個值實際上是直接在構造函數中提供的。我可以在構造函數中爲依賴屬性設置值嗎? – MatlabSorter

+1

@MatlabSorter - 我更新了我的答案,以允許傳遞給構造函數的可選自定義值。要點是使用私有屬性來存儲這個可選值,並使用get.ProblemProperty來決定是檢索這個私有屬性還是生成一個新值。 –

+0

@ b3謝謝,我認爲應該這樣做。我想知道爲什麼Matlab在我的實現中進行調用,所以我將把問題留出一段時間。 – MatlabSorter

1

您的解決方案工作,但它不是面向對象的精神,你混合存取方法是對象的外部形狀,裏面是什麼。

我會建議以下

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然後永遠不會保存任何地方,你必須編寫代碼標準的好處。

相關問題