翻看Vector代碼的時候,看到這么一段。
/** * Returns an enumeration of the components of this vector. The * returned {@code Enumeration} object will generate all items in * this vector. The first item generated is the item at index {@code 0}, * then the item at index {@code 1}, and so on. * * @return an enumeration of the components of this vector * @see Iterator */ public Enumeration<E> elements() { return new Enumeration<E>() { int count = 0; public boolean hasMoreElements() { return count < elementCount; } public E nextElement() { synchronized (Vector.this) { if (count < elementCount) { return elementData(count++); } } throw new NoSuchElementException("Vector Enumeration"); } }; }
Enumeration是個接口,內部定義此處不綴述。
此處用到了這種new接口的使用方法,如果有些場合,只需要臨時需要創建一個接口的實現類,上面的"技巧"可以用來簡化代碼.
在結合接口內部的方法設定,即可實現強大的處理方式,而省去很多單獨處理邏輯問題。
我們在仔細看,會發現實現的接口實例中並沒有elementCount,而elementCount是在Vector中定義的,那么如果調用該方法,返回一個接口實例,在使用該接口實例的時候,如何獲取到該值?
於是寫一個demo查看下,
會發現返回的實例里面維護了一個包含v實例成員變量的實例指向。所以在其方法實現里面可以使用到該值。(至於其如何實現的為探究,讀到此文知道的讀者可以留言,謝謝)
那么會想,是否返回一個對象都會封裝一個此類指向呢,可以自己按照此種方式寫一個試試。
Car是一個接口,按照上述方式模式實現的,存在上述所說引用;Student並沒有。
總結:
1、適當的時候巧用返回接口實例方式,可結合模式方式實現某種功能簡化;
2、是否可以利用其引用處理某些問題,什么樣的修飾符的成員變量能被引用對象實現,這種設計的初衷考慮哪些等等,值得神經的時候思考下。
3、另外new 接口方式可以當做參數傳遞。如t.inject(new Car(){
接口實現方法;
});