Android 设计模式实战手册(Kotlin 实战版)
目录
创建型模式(5种)
-
单例模式(Singleton)
-
工厂方法模式(Factory Method)
-
抽象工厂模式(Abstract Factory)
-
建造者模式(Builder)
-
原型模式(Prototype)
结构型模式(7种)
-
适配器模式(Adapter)
-
装饰器模式(Decorator)
-
代理模式(Proxy)
-
外观模式(Facade)
-
桥接模式(Bridge)
-
组合模式(Composite)
-
享元模式(Flyweight)
行为型模式(11种)
-
观察者模式(Observer)
-
策略模式(Strategy)
-
命令模式(Command)
-
模板方法模式(Template Method)
-
责任链模式(Chain of Responsibility)
-
状态模式(State)
-
解释器模式(Interpreter)
-
中介者模式(Mediator)
-
访问者模式(Visitor)
-
备忘录模式(Memento)
-
迭代器模式(Iterator)
第一部分:创建型模式
序号 | 模式 | Android 实例 |
---|---|---|
1 | 单例模式 (Singleton) | Retrofit、Glide |
2 | 工厂方法模式 (Factory Method) | Fragment.newInstance() |
3 | 抽象工厂模式 (Abstract Factory) | 不同 Theme 创建 View |
4 | 建造者模式 (Builder) | AlertDialog、OkHttp |
5 | 原型模式 (Prototype) | Bundle、Intent.clone |
1️⃣ 单例模式(Singleton)
设计意图:保证一个类只有一个实例,并提供全局访问点。
Android 场景:
-
Retrofit 单例管理网络请求
-
Glide 图片加载单例
-
App 全局配置对象
Kotlin 实战示例:
// Retrofit 单例封装
object RetrofitManager {val retrofit by lazy {retrofit2.Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(retrofit2.converter.gson.GsonConverterFactory.create()).build()}val apiService by lazy { retrofit.create(ApiService::class.java) }
}
优缺点:
-
✅ 优点:全局唯一,节省资源,懒加载可提高性能
-
❌ 缺点:难以单元测试,可能隐藏全局状态依赖
2️⃣ 工厂方法模式(Factory Method)
设计意图:定义一个创建对象的接口,由子类决定实例化哪一个类。
Android 场景:
-
Fragment.newInstance()
-
不同类型 View / ViewHolder 创建
Kotlin 实战示例:
// Fragment 工厂方法
class UserFragment : Fragment() {companion object {fun newInstance(userId: String): UserFragment {val fragment = UserFragment()val bundle = Bundle()bundle.putString("userId", userId)fragment.arguments = bundlereturn fragment}}
}
优缺点:
-
✅ 优点:解耦对象创建逻辑,增加扩展性
-
❌ 缺点:增加类的复杂度
3️⃣ 抽象工厂模式(Abstract Factory)
设计意图:提供一个创建一系列相关或依赖对象的接口,而无需指定具体类。
Android 场景:
-
不同主题风格下创建 Button / TextView / RecyclerView
Kotlin 实战示例:
interface ThemeFactory {fun createButton(): Buttonfun createTextView(): TextView
}class LightThemeFactory(val context: Context): ThemeFactory {override fun createButton() = Button(context).apply { setBackgroundColor(Color.WHITE) }override fun createTextView() = TextView(context).apply { setTextColor(Color.BLACK) }
}class DarkThemeFactory(val context: Context): ThemeFactory {override fun createButton() = Button(context).apply { setBackgroundColor(Color.BLACK) }override fun createTextView() = TextView(context).apply { setTextColor(Color.WHITE) }
}
优缺点:
-
✅ 优点:易于切换产品族
-
❌ 缺点:增加类数量,使用复杂
4️⃣ 建造者模式(Builder)
设计意图:将复杂对象的构建与表示分离,使同样的构建过程可以创建不同表示。
Android 场景:
-
AlertDialog.Builder
-
OkHttpClient.Builder
Kotlin 实战示例:
// AlertDialog 示例
val dialog