[英]Using SuperClass as reference instead of SubClass?
要實現隊列,我們為什么要使用?
Queue<Integer> q = new LinkedList<Integer>();
我的意思是超類引用,為什么我們不使用LinkedList引用?
我們有一個名為Code的設計原則,從不與具體實現接口
這里Queue是一個可以保存實現類的接口
優於上述原則的優點
1.將來很容易在多個實現之間切換
So it is always recommonded to code to interface instead of concrete implementations
如果我們不使用上述原則,我們就會失去關鍵的面向對象的概念多態性。
你應該總是嘗試用最少的不必要的限制來聲明你的變量; 通常這意味着像Queue或Collection這樣的界面。 這使您可以更輕松地更改您的實現。 我將使用集合框架中的兩個類作為我的示例,但原則是通用的。
想象一下以下目標:
我需要2個可以添加對象的集合。 而且我還需要能夠找到兩個集合中的哪些對象。 換句話說,我需要以下方法
Collection#add
Collection#retainAll
這些都在Collection內,所以任何集合都可以。 Collection是一個接口,所以我需要選擇一個具體的實現。 我一時興起選擇ArrayList。 我的代碼如下:
public static void main(String[] args){
Collection<Integer> a=new ArrayList<>();
Collection<Integer> b=new ArrayList<>();
initialise(a);
initialise(b);
testRetain(a,b);
}
public static void initialise(Collection<Integer> collection){
Random rnd=new Random();
for(int i=0;i<1000;i++){
collection.add(rnd.nextInt());
}
}
public static void testRetain(Collection<Integer> collection1, Collection<Integer> collection2){
collection1.removeAll(collection2);
}
這段代碼工作正常,完全符合我的要求。 然而; 在剖析中我發現它是一個瓶頸。 因此,我測試了Collection類的不同實現並分析了結果。
正如您所看到的,對於retainAll操作,HashSet變得更好。 所以我可以通過改變new ArrayList<>();
來改變我的實現new ArrayList<>();
到new HashSet<>();
在一個地方。 不需要改變我用過HashSet
所有其他方法,因為他們不關心,只要他們得到某種Collection
他們很高興
public static void main(String[] args){
Collection<Integer> a=new HashSet<>();
Collection<Integer> b=new HashSet<>();
initialise(a); //<--no need to alter this method
initialise(b);
testRetain(a,b); //<--no need to alter this method
}
那很容易。 現在用幾十種方法想象一個更大的應用程序; 所有這些都可以硬編碼以使用ArrayList
即使它們不需要,所有這些都需要手動更改。
To implement a Queue,why do we use?
沒有人能夠斷言這是每個人都必須遵循的模式。 你可以很好地使用
LinkedListq=new LinkedList();
經常使用上述模式的原因,因為它提供了多態性的力量。 簡而言之,您現在需要一個LinkedList
但稍后您可能需要PriorityQueue
。 要對多個具體類使用相同的引用,我們使用上面的模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.