2015-04-03 43 views
1

我的想法是與通用子通用組件(通用,因爲這是別人會用一個框架)內,它如何做優雅的MATLAB OO嵌套命名?

classdef Component < handle 
    properties 
     Subcomponents 
    end 

    methods 
    end 
end 

但這樣做的缺點是命名太爛:

comp1 = Component; 
comp1.Subcomponents.subcomp1 = Component; 

當我真的想要:

comp1 = Component; 
comp1.subcomp1 = Component; 

而且這些類仍然知道subcomp1是comp1的子組件。我怎樣才能做到這一點?謝謝。

換句話說,我想做例如Car.Wheel1Car.Wheel2而不是Car.Subcomponent.Wheel1Car.Subcomponent.Wheel2但Car仍然知道Wheel1和Wheel2是它的嵌套子組件,並且可以調用它的一些方法。

UPDATE:

我認爲這解決。我使用了dynamicprops,現在它非常棒。我有一個結構,仍然保持簡單的故障排除。謝謝你的回覆。

+0

一般於二OO要限制直接訪問對象字段 - 你考慮過使用getter方法? – athingunique 2015-04-03 03:38:28

+0

我很好,分離組件即Top.Sub {1} .Sub {1} .Sub {2}。然而,這不是人類可讀的,我不介意爲此建立一個解釋器,但仍然不知道如何。 – 2015-04-03 07:32:25

回答

1

儘管您可以在運行時定義struct的字段,但Matlab不允許對對象屬性進行相同的操作。因此,看來你被困在這兒......

...但是...

有解決方法! Matlab開發人員在最近的版本中推出了一些methods that modify the default behavior。特別是可以處理您的問題的方法subsrefsubsasgn。讓我們看看這可以回答你的問題。

首先,定義你類Component

classdef Component < handle 
    properties 
     Subcomponents 
    end 

    methods 
    end 
end 

然後,你必須添加以下方法subsasgnsubsref

function this = subsasgn(this, S, B) 

switch S.type 
    case '.' 
     if isprop(this, S.subs) 
      this.(S.subs) = B; 
     else 
      this.Subcomponents.(S.subs) = B; 
     end 

end 

function B = subsref(this, S) 

switch S.type 
    case '.' 
     if isprop(this, S.subs) 
      B = this.(S.subs); 
     else 
      B = this.Subcomponents.(S.subs); 
     end 
end 

,這是它!現在,您可以定義一個Component對象,並用它玩Subcomponents以不符合經典性質的標準語法的干擾:

comp = Component; 
comp.sub1 = Component; 
comp.sub2 = Component; 
c = comp.sub1; 

但是,請注意,comp默認的顯示不會給你在自己的子組件的任何信息:

>> comp 
comp = 

    Component with properties: 

    Subcomponents: [1x1 struct] 

你可以通過重載你的類的display方法來解決這個問題。

最後但並非最不重要:subsasgnsubsref允許您控制對象的語法(括號,括號等),所以您可以使用這兩種方法來做更酷的事情!

+0

這是一個非常不必要的方法。重載'subsref'和'subsasgn'是一種很少需要的高級技術,除非您特別需要修改對象數組的引用和分配行爲。這裏肯定不需要。順便說一句,它也不是最近推出的功能:它現在已經出現在許多版本中。 – 2015-04-03 20:51:33

+1

PS如果您確實需要動態地添加或刪除類屬性,則執行此操作的方法是從'dynamicprops'繼承,而不是重載'subsref'和'subsasgn'。爲了自定義顯示,最好從matlab.mixin.CustomDisplay繼承,而不是重載display。 – 2015-04-03 20:57:17

+0

感謝你們倆。但是,哪個更容易實現? dynamicprops或subsref/subsasgn?另外,哪個更容易調試? – 2015-04-04 02:56:16

0

我建議只是使​​屬性的數組,所以你可以說

comp = Component 
comp.subcomponents(1) = Component 
+0

訪問像輪子這樣的子組件會是Car.subcomponents(1)?我怎樣才能使用它的名字,這將是Car.Wheel1 – 2015-04-04 02:55:08

+0

如果你願意,你可以有一個屬性'wheel1',設置爲'Component',然後你也可以有一個屬性'subComponents',它是數組。如果你願意,你可以將'subComponents'屬性設置爲'Dependent'和'SetAccess = private',並給它一個'get'方法,返回包含'wheel1'和你定義的其他子組件的數組。 – 2015-04-09 12:23:48