【Android】源码中的工厂方法模式

本文是基于 Android 14 的源码解析

工厂方法模式应用很广泛,我们平时开发中经常会使用到的数据结构中其实也隐藏着对工厂方法模式的应用,以 List 和 Set 为例,List 和 Set 都继承于 Collection 接口,而 Collection 接口继承于 Iterable 接口,Iterable 接口如下:

java 复制代码
public interface Iterable<T> {
    Iterator<T> iterator();
    
    ...
}

这意味着 List 和 Set 接口也会继承该方法,平时比较常用的两个间接实现类 ArrayList 和 HashSet 中 iterator 方法的实现就是构造并返回一个迭代器对象:

java 复制代码
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    public Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {
        int cursor = 0;

        int lastRet = -1;

        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size();
        }

        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException(e);
            }
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
}
java 复制代码
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable {
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }
}

HashSet 的 iterator 方法中会返回成员变量 map 中对应 HashSet 对象元素的迭代器对象,最终返回的是 KeySet 中的一个迭代器对象:

java 复制代码
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
    final class KeySet extends AbstractSet<K> {
        public final Iterator<K> iterator() {
            return new KeyIterator();
        }
    }
}

ArrayList 和 HashSet 中的 iterator 方法其实就相当于一个工厂方法,专为 new 对象而生,这里 iterator 方法是构造并返回一个具体的迭代器。

Android 中对工厂方法模式的应用更多,相信以下代码对一个 Android 新手来说都不陌生:

kt 复制代码
class TestAActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

实质上,onCreate 方法就相当于一个工厂方法,在 TestAActivity 的 onCreate 方法中构造一个 View 对象,并设置为当前界面的 ContentView 返回给 Framework 处理,如果现在又有一个 TestBActivity,这时我们又在其 onCreate 方法中通过 setContentView 方法设置另外不同的 View,这是不是就是一个工厂模式的结构呢?其实设计模式离我们非常近!

相关推荐
巧克力芋泥包22 分钟前
前端使用阿里云图形验证码;并且与安卓进行交互
android·前端·阿里云
Just_Paranoid3 小时前
【MQTT】基于 Android 设备接入物联网平台最佳实践
android·mqtt·eclipse·iot·paho·mqtt.fx
alexhilton6 小时前
深入理解withContext和launch的真正区别
android·kotlin·android jetpack
ACE19858 小时前
AI Agent 设计模式深度解析:提示链(Prompt Chaining)模式
人工智能·设计模式·prompt
明洞日记10 小时前
【设计模式手册012】责任链模式 - 请求处理的流水线艺术
java·设计模式·责任链模式
ada0_ada110 小时前
行为型模式:①责任链模式(Chain of Responsibility Pattern)
设计模式
TDengine (老段)10 小时前
TDengine 转换函数 TO_JSON 用户手册
android·大数据·数据库·json·时序数据库·tdengine·涛思数据
q***428210 小时前
SpringCloudGateWay
android·前端·后端
卫生纸不够用10 小时前
Appium-锁屏-Android
android·appium
阿拉斯攀登10 小时前
安卓工控机 OTA 升级方案(SpringBoot+MQTT)
android·spring boot·物联网·iot