3 回答

TA貢獻1847條經驗 獲得超11個贊
您可能正在尋找這樣的東西:
public static void main(String... args) {
// do this - declare the variable to be of type Set, which is an interface
Set buddies = new HashSet();
// don't do this - you declare the variable to have a fixed type
HashSet buddies2 = new HashSet();
}
為什么第一種方法被認為是好的?稍后再說,您決定需要使用其他數據結構,例如LinkedHashSet,以便利用LinkedHashSet的功能。必須更改代碼,如下所示:
public static void main(String... args) {
// do this - declare the variable to be of type Set, which is an interface
Set buddies = new LinkedHashSet(); // <- change the constructor call
// don't do this - you declare the variable to have a fixed type
// this you have to change both the variable type and the constructor call
// HashSet buddies2 = new HashSet(); // old version
LinkedHashSet buddies2 = new LinkedHashSet();
}
這看起來還不錯,對吧?但是,如果您以同樣的方式編寫吸氣劑怎么辦?
public HashSet getBuddies() {
return buddies;
}
這也必須更改!
public LinkedHashSet getBuddies() {
return buddies;
}
希望您能看到,即使使用像這樣的小程序,也對聲明變量類型具有深遠的影響。如果僅依賴于將變量聲明為接口,而不是作為該接口的特定實現(在這種情況下,將其聲明為接口),那么對象的來回移動無疑會大大簡化程序的編寫和維護。集,而不是LinkedHashSet或其他值)。可能就是這樣:
public Set getBuddies() {
return buddies;
}
另一個好處是,(至少對我而言)差異有助于我更好地設計程序。但是希望我的示例可以給您一些想法...希望能有所幫助。

TA貢獻1799條經驗 獲得超8個贊
一天,他的老板指示一名初級程序員編寫一個應用程序來分析業務數據,并將其匯總為帶有指標,圖形和所有其他內容的漂亮報告。老板給他一個XML文件,上面寫著“這是一些示例業務數據”。
程序員開始編碼。幾周后,他覺得度量,圖形和內容足以使老板滿意,于是他介紹了他的工作。老板說:“那太好了,但是它還能顯示我們擁有的這個SQL數據庫中的業務數據嗎?”
程序員回到編碼。在他的整個應用程序中都有用于從XML讀取業務數據的代碼。他重寫了所有這些代碼片段,并以“ if”條件包裝它們:
if (dataType == "XML")
{
... read a piece of XML data ...
}
else
{
.. query something from the SQL database ...
}
當看到該軟件的新版本時,老板回答:“太好了,但是它還能報告來自該Web服務的業務數據嗎?” 記住所有那些他必須重寫的乏味的if語句,程序員變得很生氣?!笆紫仁莤ml,然后是SQL,現在是Web服務!真正的業務數據源是什么?”
老板回答:“任何可以提供的東西”
那時,程序員很受啟發。
添加回答
舉報