Android开发中常用设计模式
:InputStream增强(BufferedInputStream)、View功能扩展。:Android事件分发(ViewGroup→View)、拦截器链(OkHttp)。:RecyclerView.Adapter(数据→视图)、第三方库适配。:为其他对象提供代理以控制访问(如延迟加载、权限校验)。:Glide图片加载(隐藏复杂初始化)、AOP编程。:创建复杂对象(如网络请求库)、U
一、创建型模式
1. 单例模式 (Singleton)
意图:确保类仅有一个实例,并提供全局访问点。
场景:资源管理器(数据库、网络)、配置类。
实现方式:
// Java双检锁实现
public class DatabaseManager {
private static volatile DatabaseManager instance;
private DatabaseManager() {} // 私有构造
public static DatabaseManager getInstance() {
if (instance == null) {
synchronized (DatabaseManager.class) {
if (instance == null) {
instance = new DatabaseManager();
}
}
}
return instance;
}
}
// Kotlin对象声明(推荐)
object DatabaseManager {
fun query() { ... }
}
优点:节省资源、全局访问;缺点:单元测试困难、职责过重。
2. 工厂方法模式 (Factory Method)
意图:将对象创建委托给子类,解耦调用方与具体类。
场景:创建复杂对象(如网络请求库)、UI组件生成。
示例:
// Kotlin接口工厂
interface ApiClient {
fun request(): Response
}
class OkHttpClient : ApiClient { ... }
class RetrofitClient : ApiClient { ... }
object ClientFactory {
fun create(type: String): ApiClient {
return when (type) {
"okhttp" -> OkHttpClient()
"retrofit" -> RetrofitClient()
else -> throw IllegalArgumentException()
}
}
}
扩展:抽象工厂模式(创建产品族,如不同主题UI组件)。
3. 建造者模式 (Builder)
意图:分离复杂对象的构建与表示,支持逐步构造。
场景:AlertDialog配置、Retrofit构建。
示例:
// Java实现
public class User {
private final String name;
private final int age;
private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
}
public static class Builder {
private String name;
private int age = 0;
public Builder setName(String name) {
this.name = name;
return this;
}
public User build() {
return new User(this);
}
}
}
// 使用:new User.Builder().setName("Tom").build();
二、结构型模式
4. 适配器模式 (Adapter)
意图:转换接口,使不兼容类能协同工作。
场景:RecyclerView.Adapter(数据→视图)、第三方库适配。
示例:
// Kotlin适配器
class WeatherAdapter(private val data: List<WeatherData>) : RecyclerView.Adapter<WeatherViewHolder>() {
override fun onBindViewHolder(holder: WeatherViewHolder, position: Int) {
val item = data[position]
holder.bind(item) // 将数据适配到ViewHolder
}
}
5. 装饰者模式 (Decorator)
意图:动态添加功能,避免子类爆炸。
场景:InputStream增强(BufferedInputStream)、View功能扩展。
示例:
// Java I/O装饰者示例
FileInputStream fis = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(fis); // 添加缓冲功能
6. 代理模式 (Proxy)
意图:为其他对象提供代理以控制访问(如延迟加载、权限校验)。
场景:Glide图片加载(隐藏复杂初始化)、AOP编程。
示例:
// Kotlin延迟代理
val heavyObject: HeavyClass by lazy {
HeavyClass() // 首次访问时初始化
}
三、行为型模式
7. 观察者模式 (Observer)
意图:定义一对多依赖,状态变更时自动通知。
场景:LiveData、RxJava、事件总线。
示例:
// Java自定义观察者
public interface NetworkListener {
void onNetworkChanged(boolean isConnected);
}
public class NetworkManager {
private List<NetworkListener> listeners = new ArrayList<>();
public void addListener(NetworkListener listener) {
listeners.add(listener);
}
private void notifyListeners() {
for (NetworkListener listener : listeners) {
listener.onNetworkChanged(isConnected);
}
}
}
8. 策略模式 (Strategy)
意图:封装算法族,使其可互换。
场景:排序算法切换、支付方式选择。
示例:
// Kotlin策略接口
interface PaymentStrategy {
fun pay(amount: Double)
}
class CreditCardStrategy : PaymentStrategy { ... }
class AlipayStrategy : PaymentStrategy { ... }
class PaymentContext(var strategy: PaymentStrategy) {
fun executePay(amount: Double) {
strategy.pay(amount)
}
}
// 使用:context.strategy = AlipayStrategy(); context.executePay(100.0)
9. 模板方法模式 (Template Method)
意图:定义算法骨架,子类重写特定步骤。
场景:AsyncTask(doInBackground()
)、BaseActivity生命周期。
示例:
public abstract class BaseFragment {
// 模板方法(final防止重写)
public final void init() {
loadConfig();
initViews();
loadData();
}
protected abstract void initViews(); // 子类实现
protected void loadConfig() { ... } // 默认实现
}
10. 命令模式 (Command)
意图:封装请求为对象,支持撤销/重做。
场景:点击事件封装、事务操作。
示例:
interface Command {
fun execute()
fun undo()
}
class LightOnCommand(private val light: Light) : Command {
override fun execute() { light.on() }
override fun undo() { light.off() }
}
class RemoteControl {
private val commandStack = Stack<Command>()
fun pressButton(command: Command) {
command.execute()
commandStack.push(command)
}
fun undo() {
if (commandStack.isNotEmpty()) commandStack.pop().undo()
}
}
四、其他关键模式
11. 状态模式 (State)
意图:允许对象在内部状态改变时变更行为。
场景:播放器状态(播放/暂停)、订单状态流转。
核心:将状态抽象为接口,行为委托给当前状态对象。
12. 责任链模式 (Chain of Responsibility)
意图:多个对象依次处理请求,避免发送者与接收者耦合。
场景:Android事件分发(ViewGroup→View)、拦截器链(OkHttp)。
关键代码:
public abstract class Handler {
private Handler next;
public void setNext(Handler next) { ... }
public void handle(Request request) {
if (canHandle(request)) process(request);
else if (next != null) next.handle(request);
}
protected abstract boolean canHandle(Request request);
}
五、模式选择与对比
模式 | 使用率 | 典型场景 | 优势 |
---|---|---|---|
单例 | ⭐⭐⭐⭐⭐ | 全局资源管理 | 节省资源、避免重复创建 |
观察者 | ⭐⭐⭐⭐⭐ | 数据监听、事件通知 | 解耦发布者与订阅者 |
适配器 | ⭐⭐⭐⭐ | 列表数据绑定、接口兼容 | 增强复用性 |
建造者 | ⭐⭐⭐⭐ | 复杂对象构造 | 灵活支持可选参数、链式调用 |
策略 | ⭐⭐⭐ | 算法动态切换 | 避免条件语句、符合开闭原则 |
最佳实践:
- 避免滥用单例:改用依赖注入(如Dagger)管理全局状态
- 优先组合而非继承:装饰者/策略模式比子类化更灵活
- Android特有适配:LiveData(观察者)、ViewModel(状态管理)已内置模式实现
更多推荐
所有评论(0)