Android源码中的设计模式
- 单例模式
-
懒汉式单例
frameworks\base\core\java\android\bluetooth\BluetoothAdapter.java
public final class BluetoothAdapter { /** * Lazily initialized singleton. Guaranteed final after first object * constructed. */ private static BluetoothAdapter sAdapter public static synchronized BluetoothAdapter getDefaultAdapter() { if (sAdapter == null) { IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE); if (b != null) { IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b); sAdapter = new BluetoothAdapter(managerService); } else { Log.e(TAG, "Bluetooth binder is null"); } } return sAdapter; } /** * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance. */ BluetoothAdapter(IBluetoothManager managerService) { ... } }
-
访问器模式
Context上下文是一个很好的访问器模式例子,其相关类图如下,具体角色为:
抽象元素(接口):Context具体的元素:ContextImpl
抽象访问器(接口):Context
具体的访问器:ContextWrapper
(附:推荐博文Android应用上下文Context · 语雀)
-
观察者模式
-
命令模式