2013-10-16 38 views
2

我們正在使用XML,並希望在主要XML類及其所有組件之間建立一個通用接口。但是,XML類的子組件需要其他方法,但它們也需要主要組件的方法。似乎對繼承有很大的用處。僞造組合和通用接口

這是我寫的一些代碼來完成這項任務。希望你可以得到我們根據使用情況要什麼的一個好主意:

using System; 

namespace SampleNamespace 
{ 
    public class SampleClass 
    { 
     public static void Main() 
     { 

      var xmlDocumentFiles = new XmlDocumentFiles(); 

      xmlDocumentFiles.Files.RootFile.SetFileName("Example.xml"); 

      System.Console.WriteLine(
       xmlDocumentFiles.Files.RootFile.GetFileName() 
      ); 

     } 
    } 

    public class XmlDocumentFilesRoot 
    { 
     protected string _rootFileName; 

     public FilesClass Files { get { return (FilesClass) this; } } 
    } 

    public class FilesClass : XmlDocumentFilesRoot 
    { 
     public RootFileClass RootFile { get { return (RootFileClass) this; } } 
    } 

    public class RootFileClass : FilesClass 
    { 
     public void SetFileName(string newTitle) 
     { 
      _rootFileName = newTitle; 
     } 

     public string GetFileName() 
     { 
      return _rootFileName; 
     } 
    } 

    public class XmlDocumentFiles : RootFileClass 
    { 
    } 

} 

我能投給子類和我吃驚的是它運行得很好。假設除了父類中沒有意義的方法以外,什麼都不放在子類中,那麼這個類結構會不會有任何問題(奇怪的編譯錯誤,運行時崩潰)?

有沒有其他的選擇?我最初嘗試位於主類之外的嵌套類+擴展方法,但是需要很多代碼來設置它。請參閱:https://stackoverflow.com/questions/19415717/using-c-sharp-extension-methods-on-not-in-nested-classes-to-establish-a-common

回答

1

擴展類的功能,聽起來像裝飾者模式。

下面是關於這一主題的頭一PDF: http://oreilly.com/catalog/hfdesignpat/chapter/ch03.pdf

也;我想勸阻三重奏'。' :

xmlDocumentFiles.Files.RootFile.SetFileName("Example.xml"); 

2是邪惡的,如果你需要3:你一定會失去可維護性。

希望它有幫助。

+0

真的嗎?你知道,我並不完全不同意,但我們的希望實際上是,這種模式可以通過不用一大堆不同的方法混淆一個班級而提供一些關注的分離。 –

+0

@AlexanderPritchard:想象一下:如果你繼續這種方法,你最終會使用4,5或6個點。想象一下對象返回一個'null'值,你會得到一個NullReferenceException。這在某些情況下很難調試。它可能會變得更糟:如果您在某處返回了一個IDisposable,您何時會執行該處置? ......更糟糕的是:在某個地方返回一個Com對象(我真的看到這個例子只有一次):你什麼時候打電話給Marshall.Resease如果需要的話? – Stefan

+0

@AlexanderPritchard:對於裝飾器模式的一個非常好的例子,請看看.net Stream類。有很多不同的類型(MemoryStream,StreamReader,StreamWriter,Images,HttpResponses等),都暴露他們自己的方法,或者實現他們自己的(例如寫)覆蓋。它具有類中的各種額外功能,而不會丟失基類功能。結合界面也很容易,所以你甚至不會堅持一個類的具體實現:)我真的認爲你應該在這種情況下考慮這種基本模式。 – Stefan