天天看點

Android 源碼的工廠方法模式Android 源碼的工廠方法模式

Android 源碼的工廠方法模式

工廠方法模式介紹

工廠方法模式(Factory Pattern),是建立型設計模式之一。工廠方法模式是一種結構簡單的模式,比如 Android 中的 Activity 裡的各個生命周期方法,以 onCreate 方法為例,它可以看作是一個工廠方法,我們在其中可以構造 View,通過 setContentView 傳回給 framework 處理。

工廠方法模式的定義

工廠方法模式定義一個用于建立對象的接口,讓子類決定執行個體化哪個類。

Iterable

以 List 和 Set 為例,List 和 Set 都繼承于 Collection 接口,而 Collection 接口繼承于 Iterable 接口,Iterable 接口很簡單,有一個 iterator 方法。Java 1.8 定義了 forEach 和 spliterator 方法。

public interface Iterable<T> {
    Iterator<T> iterator();
    ...
}
           

ArrayList

ArrayList 實作了 iterator 方法,傳回一個 Itr 疊代器對象。

public Iterator<E> iterator() {
        return new Itr();
    }
           
private class Itr implements Iterator<E> {
        ...
        protected int limit = ArrayList.this.size;

        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor < limit;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            int i = cursor;
            if (i >= limit)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
                limit--;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;

            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
           

Itr 疊代器對象提供了 hasNext、next、remove、forEachRemaining 的實作。

HashSet

HashSet 的 iterator 方法傳回了它的成員變量 map 的 keySet 的 疊代器對象。

public Iterator<E> iterator() {
        return map.keySet().iterator();
    }
           
final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        ...
    }
           

KeySet 的 iterator 方法傳回了一個 KeyIterator。

onCreate

Android 的 Activity 的 onCreate 方法是一個工廠方法模式。

public class AActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);
    }
}
           

我們在 AActivity 的 onCreate 方法中得到一個 View,并且設定為目前界面的 ContentView 傳回給 framework 處理,如果現在又有一個 BActvity,隻需要在其 onCreate 通過 setContentView 設定另外的 View,這是一個工廠模式的結構。