2010-08-28 83 views
2

假設有您需要實現業務功能,這臺某種輪廓。簡單的繼承

根據數據如何接收,但可以設置個人資料將被不同的方式實現。

例如參數可以直接傳遞給將能夠

setProfile(); 

或對象,參數必須被發現,並就必須通過由

setProfile(String[] data, Blah blooh); 

個人資料在這種情況下最好的方法是什麼?我的意思是,設計明智你將如何構建這個?

我想使用接口與抽象方法,它的工作原理,但引入了一些噪音。不確定如何最好地構造這個。

回答

3

我會通過抽象的實際輪廓,以自己的類層次結構封裝,並添加泛型到setProfile()去。當然,它確實增加了一些複雜性,但是因爲它也引入了間接性,所以代碼將更加分離,從長遠來看應該證明是有用的。

此外,實際的功能也可能在其自己的類層次結構中,從而使該部分可插入,這意味着您的手中會有Strategy Pattern。然而,應用這個決定需要更多關於你正在構建的系統的知識,並且可能不適合你正在構建的系統。

快速例如:

/** 
* Interface for describing the actual function. May (and most likely does) 
* contain other methods too. 
*/ 
public interface BusinessFunction<P extends Profile> { 
    public void setProfile(P p); 
} 

/** 
* Base profile interface, contains all common profile related methods. 
*/ 
public interface Profile {} 

/** 
* This interface is mostly a matter of taste, I added this just to show the 
* extendability. 
*/ 
public interface SimpleProfile extends Profile {} 

/** 
* This would be what you're interested of. 
*/ 
public interface ComplexProfile extends Profile { 
    String[] getData(); 
    Blah blooh(); 
} 

/** 
* Actual function. 
*/ 
public class ComplexBusinessFunction implements BusinessFunction<ComplexProfile> { 
    public void setProfile(ComplexProfile p) { 
     // do whatever with p which has getData() and blooh() 
    } 
} 

/** 
* And another example just to be thorough. 
*/ 
public class SimpleBusinessFunction implements BusinessFunction<SimpleProfile> { 
    public void setProfile(SimpleProfile p) { 
     // do whatever with the empty profile 
    } 
} 
+0

愛它。謝謝 – JAM 2010-08-28 16:12:28

5

我總是很緊張周圍有許多重載方法。我比較喜歡,在這種情況下,想方法參數的消息,而不是參數,並建立一個單一的方法,像這樣:

setProfile(ProfileData data) 

ProfileData類可以包含在所有的你setProfile辦法制定共同的數據,並且可以爲專門的setProfile操作創建派生類。

這種方法如果使用的是序列化技術,可以自動地堅持基於其結構中的ProfileData對象時特別有用。

0

對於get/set方法,我始終保持在設定的方法作爲一個單一的輸入。不要只是一個簡單的對象,可能是一個更復雜的對象,正如kbirmington所建議的那樣。我認爲我比其他任何真正的設計優勢都要做得更好。

它值得記住不過,如果配置文件數據有10個屬性,他們只提供9折他們,有可能你會寫在此基礎上的10個屬性,實際上是缺少9種不同的方法。

至少具有單一結構中,存在一個輸入,而且如果結構改變方法確實裏面不僅該代碼。

在這方面你是編程到這是一個很好的設計模式的界面。