面试题 - Android - 设计模式

209 阅读5分钟

我很乐意为您总结Android中的设计模式应用。根据文章内容,我将重点介绍几个在Android开发中常用的设计模式:

设计模式在Android的应用

1. 单例模式 (Singleton Pattern)

最常用的设计模式之一,在Android中的应用场景:

  • SharedPreferences实例
  • 数据库Helper类
  • 全局Context
  • 各种Manager类
public class SingletonManager {
    private static SingletonManager instance;
    
    private SingletonManager() {}
    
    public static synchronized SingletonManager getInstance() {
        if (instance == null) {
            instance = new SingletonManager();
        }
        return instance;
    }
}

2. 观察者模式 (Observer Pattern)

在Android中广泛应用:

  • LiveData
  • EventBus
  • BroadcastReceiver
  • OnClickListener
// 简化示例
public class DataManager extends Observable {
    private Data data;
    
    public void setData(Data data) {
        this.data = data;
        setChanged();
        notifyObservers(data);
    }
}

3. 建造者模式 (Builder Pattern)

常见于:

  • AlertDialog.Builder
  • Retrofit.Builder
  • OkHttpClient.Builder
AlertDialog.Builder builder = new AlertDialog.Builder(context)
    .setTitle("标题")
    .setMessage("内容")
    .setPositiveButton("确定", null)
    .setNegativeButton("取消", null);

4. 工厂模式 (Factory Pattern)

应用场景:

  • Fragment.instantiate()
  • LayoutInflater
  • Intent创建
public class ViewFactory {
    public static View createView(Context context, String type) {
        switch (type) {
            case "button":
                return new Button(context);
            case "textview":
                return new TextView(context);
            default:
                return null;
        }
    }
}

5. 适配器模式 (Adapter Pattern)

最典型的应用:

  • RecyclerView.Adapter
  • ListView.Adapter
  • ViewPager.Adapter
public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {
    // 实现相关方法
    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 创建ViewHolder
    }
    
    @Override
    public void onBindViewHolder(CustomViewHolder holder, int position) {
        // 绑定数据
    }
}

流程图

以观察者模式为例:

graph TD
    A[被观察者/Subject] -->|通知| B[观察者1/Observer]
    A -->|通知| C[观察者2/Observer]
    A -->|通知| D[观察者3/Observer]
    E[数据更新] -->|触发| A

总结

设计模式在Android开发中的应用非常广泛,它们能够:

  1. 提高代码的可复用性
  2. 增强系统的可维护性
  3. 使代码结构更清晰
  4. 降低系统的耦合度

深度分析

1. 单例模式的深度解析

单例模式在Android中极其重要,但需要注意以下关键点:

// 推荐的双重检查锁定实现
public class Singleton {
    // volatile关键字确保instance变量的可见性,防止指令重排
    private volatile static Singleton instance;
    
    // 私有构造函数防止外部实例化
    private Singleton() {
        // 防止反射攻击
        if (instance != null) {
            throw new RuntimeException("Cannot create second instance");
        }
    }
    
    public static Singleton getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (Singleton.class) { // 同步锁
                if (instance == null) { // 第二次检查
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
    
    // 防止序列化攻击
    protected Object readResolve() {
        return instance;
    }
}

在Android中的实际应用:

// 数据库管理器示例
public class DatabaseManager {
    private volatile static DatabaseManager instance;
    private SQLiteDatabase db;
    private final Context context;

    private DatabaseManager(Context context) {
        this.context = context.getApplicationContext(); // 使用Application Context避免内存泄漏
        initDatabase();
    }

    public static DatabaseManager getInstance(Context context) {
        if (instance == null) {
            synchronized (DatabaseManager.class) {
                if (instance == null) {
                    instance = new DatabaseManager(context);
                }
            }
        }
        return instance;
    }

    @WorkerThread
    private void initDatabase() {
        // 数据库初始化操作
    }
}

2. 面向对象六大原则在Android中的实践

以MVVM架构为例展示原则应用:

// 单一职责原则示例
class UserRepository {
    private val apiService: ApiService
    private val userDao: UserDao
    
    suspend fun getUser(userId: String): User {
        // 数据获取逻辑
        return withContext(Dispatchers.IO) {
            val localUser = userDao.getUser(userId)
            if (localUser != null) {
                localUser
            } else {
                val remoteUser = apiService.getUser(userId)
                userDao.insertUser(remoteUser)
                remoteUser
            }
        }
    }
}

// 依赖倒置原则示例
interface UserDataSource {
    suspend fun getUser(userId: String): User
}

class RemoteUserDataSource @Inject constructor(
    private val apiService: ApiService
) : UserDataSource {
    override suspend fun getUser(userId: String) = apiService.getUser(userId)
}

class LocalUserDataSource @Inject constructor(
    private val userDao: UserDao
) : UserDataSource {
    override suspend fun getUser(userId: String) = userDao.getUser(userId)
}

3. 工厂模式的高级应用

ViewModelProvider.Factory的实现示例:

class ViewModelFactory @Inject constructor(
    private val repository: UserRepository
) : ViewModelProvider.Factory {
    
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return when {
            modelClass.isAssignableFrom(UserViewModel::class.java) -> {
                UserViewModel(repository) as T
            }
            modelClass.isAssignableFrom(SettingsViewModel::class.java) -> {
                SettingsViewModel(repository) as T
            }
            else -> throw IllegalArgumentException("Unknown ViewModel class")
        }
    }
}

4. 责任链模式在网络请求中的应用

基于OkHttp的自定义拦截器链:

class RequestInterceptorChain {
    private val interceptors = ArrayList<Interceptor>()
    
    fun addInterceptor(interceptor: Interceptor) {
        interceptors.add(interceptor)
    }
    
    fun proceed(request: Request): Response {
        var processedRequest = request
        for (interceptor in interceptors) {
            processedRequest = interceptor.intercept(processedRequest)
        }
        return executeRequest(processedRequest)
    }
}

// 认证拦截器
class AuthInterceptor : Interceptor {
    override fun intercept(request: Request): Request {
        return request.newBuilder()
            .addHeader("Authorization", "Bearer ${getToken()}")
            .build()
    }
}

// 缓存拦截器
class CacheInterceptor : Interceptor {
    override fun intercept(request: Request): Request {
        val cached = cache.get(request.url)
        if (cached != null && !cached.isExpired()) {
            return cached
        }
        return request
    }
}

5. 观察者模式与响应式编程

使用Flow实现MVVM架构:

class UserViewModel @Inject constructor(
    private val userRepository: UserRepository
) : ViewModel() {

    private val _userState = MutableStateFlow<UserState>(UserState.Initial)
    val userState: StateFlow<UserState> = _userState.asStateFlow()

    fun fetchUser(userId: String) {
        viewModelScope.launch {
            _userState.value = UserState.Loading
            try {
                val user = userRepository.getUser(userId)
                _userState.value = UserState.Success(user)
            } catch (e: Exception) {
                _userState.value = UserState.Error(e.message)
            }
        }
    }
}

sealed class UserState {
    object Initial : UserState()
    object Loading : UserState()
    data class Success(val user: User) : UserState()
    data class Error(val message: String?) : UserState()
}

6. 代理模式在Android架构组件中的应用

LiveData委托属性实现:

class LiveDataDelegate<T>(
    private val initialValue: T
) : ReadWriteProperty<LifecycleOwner, T> {
    
    private val liveData = MutableLiveData(initialValue)
    
    override fun getValue(thisRef: LifecycleOwner, property: KProperty<*>): T {
        return liveData.value ?: initialValue
    }
    
    override fun setValue(thisRef: LifecycleOwner, property: KProperty<*>, value: T) {
        liveData.value = value
    }
}

// 使用示例
class MainActivity : AppCompatActivity() {
    private var userName by LiveDataDelegate("")
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        userName = "New Value" // 自动触发UI更新
    }
}

7. 建造者模式在网络请求中的应用

自定义网络请求构建器:

class NetworkRequestBuilder {
    private var url: String? = null
    private var method: String = "GET"
    private val headers = mutableMapOf<String, String>()
    private var body: RequestBody? = null
    private var timeout: Long = 30_000
    
    fun url(url: String) = apply { this.url = url }
    fun method(method: String) = apply { this.method = method }
    fun addHeader(key: String, value: String) = apply { headers[key] = value }
    fun body(body: RequestBody) = apply { this.body = body }
    fun timeout(timeout: Long) = apply { this.timeout = timeout }
    
    fun build(): NetworkRequest {
        requireNotNull(url) { "URL must not be null" }
        return NetworkRequest(
            url = url!!,
            method = method,
            headers = headers.toMap(),
            body = body,
            timeout = timeout
        )
    }
}

// 使用示例
val request = NetworkRequestBuilder()
    .url("https://api.example.com/users")
    .method("POST")
    .addHeader("Content-Type", "application/json")
    .body(jsonBody)
    .timeout(5000)
    .build()

8. 原型模式的深度实现与应用

在Android中,原型模式常用于对象的深度复制,特别是在处理复杂UI状态时:

// 使用数据类的copy方法实现原型模式
data class UiState(
    val userId: String,
    val userData: UserData,
    val preferences: UserPreferences
) : Cloneable {
    // 深拷贝实现
    public override fun clone(): UiState {
        return copy(
            userId = userId,
            userData = userData.copy(),
            preferences = preferences.copy()
        )
    }
}

// 在ViewModel中的应用
class ProfileViewModel : ViewModel() {
    private val _uiState = MutableStateFlow<UiState>(UiState.Initial)
    
    fun updateUserPreferences(newPreferences: UserPreferences) {
        viewModelScope.launch {
            // 使用原型模式创建新状态
            val newState = _uiState.value.clone().copy(
                preferences = newPreferences
            )
            _uiState.value = newState
        }
    }
}

9. 策略模式在Android中的高级应用

策略模式在Android中常用于处理不同的业务逻辑实现:

// 支付策略接口
interface PaymentStrategy {
    suspend fun processPayment(amount: BigDecimal): PaymentResult
}

// 具体支付实现
class WeChatPayStrategy @Inject constructor(
    private val weChatPayApi: WeChatPayApi,
    private val paymentRepository: PaymentRepository
) : PaymentStrategy {
    override suspend fun processPayment(amount: BigDecimal): PaymentResult {
        return withContext(Dispatchers.IO) {
            try {
                val order = weChatPayApi.createOrder(amount)
                paymentRepository.savePaymentRecord(order)
                PaymentResult.Success(order)
            } catch (e: Exception) {
                PaymentResult.Error(e)
            }
        }
    }
}

// 支付处理器
class PaymentProcessor @Inject constructor(
    private val strategies: Map<PaymentType, @JvmSuppressWildcards PaymentStrategy>
) {
    suspend fun processPayment(
        type: PaymentType,
        amount: BigDecimal
    ): PaymentResult {
        return strategies[type]?.processPayment(amount)
            ?: throw IllegalArgumentException("Unsupported payment type")
    }
}

// Dagger注入配置
@Module
class PaymentModule {
    @Provides
    @IntoMap
    @PaymentTypeKey(PaymentType.WECHAT)
    fun provideWeChatStrategy(
        impl: WeChatPayStrategy
    ): PaymentStrategy = impl
}

10. 静态代理与动态代理的高级应用

静态代理在权限检查中的应用:
// 接口定义
interface UserOperations {
    suspend fun getUserData(userId: String): UserData
    suspend fun updateUserProfile(profile: UserProfile)
}

// 实际实现
class UserOperationsImpl @Inject constructor(
    private val userApi: UserApi,
    private val userDao: UserDao
) : UserOperations {
    override suspend fun getUserData(userId: String): UserData = // 实现
    override suspend fun updateUserProfile(profile: UserProfile) = // 实现
}

// 权限检查代理
class PermissionCheckProxy @Inject constructor(
    private val operations: UserOperations,
    private val permissionChecker: PermissionChecker
) : UserOperations {
    override suspend fun getUserData(userId: String): UserData {
        checkPermission(Permission.READ_USER_DATA)
        return operations.getUserData(userId)
    }

    override suspend fun updateUserProfile(profile: UserProfile) {
        checkPermission(Permission.WRITE_USER_DATA)
        operations.updateUserProfile(profile)
    }

    private fun checkPermission(permission: Permission) {
        if (!permissionChecker.hasPermission(permission)) {
            throw SecurityException("Permission denied: $permission")
        }
    }
}
动态代理在网络请求缓存中的应用:
class ApiServiceProxy(
    private val cacheManager: CacheManager,
    private val networkMonitor: NetworkMonitor
) {
    inline fun <reified T> create(service: Class<T>): T {
        return Proxy.newProxyInstance(
            service.classLoader,
            arrayOf(service)
        ) { _, method, args ->
            // 获取缓存注解
            val cacheConfig = method.getAnnotation(Cached::class.java)
            
            if (cacheConfig != null) {
                // 检查缓存
                val cacheKey = generateCacheKey(method, args)
                val cachedResult = cacheManager.get(cacheKey)
                
                if (cachedResult != null && !cacheConfig.forceRefresh) {
                    return@newProxyInstance cachedResult
                }
            }
            
            // 执行实际请求
            val result = method.invoke(service, *args)
            
            // 存储缓存
            if (cacheConfig != null) {
                cacheManager.put(cacheKey, result)
            }
            
            result
        } as T
    }
}

11. 责任链模式在请求处理中的高级应用

// 请求处理器接口
interface RequestHandler {
    suspend fun handle(request: Request): Response?
    fun setNext(handler: RequestHandler): RequestHandler
}

// 抽象处理器
abstract class BaseRequestHandler : RequestHandler {
    private var nextHandler: RequestHandler? = null
    
    override fun setNext(handler: RequestHandler): RequestHandler {
        nextHandler = handler
        return handler
    }
    
    override suspend fun handle(request: Request): Response? {
        val response = processRequest(request)
        if (response != null) return response
        return nextHandler?.handle(request)
    }
    
    protected abstract suspend fun processRequest(request: Request): Response?
}

// 缓存处理器
class CacheHandler @Inject constructor(
    private val cacheManager: CacheManager
) : BaseRequestHandler() {
    override suspend fun processRequest(request: Request): Response? {
        return cacheManager.get(request.cacheKey)
    }
}

// 网络处理器
class NetworkHandler @Inject constructor(
    private val apiService: ApiService
) : BaseRequestHandler() {
    override suspend fun processRequest(request: Request): Response? {
        return apiService.execute(request)
    }
}

// 错误处理器
class ErrorHandler : BaseRequestHandler() {
    override suspend fun processRequest(request: Request): Response? {
        return Response.Error("Request failed after all handlers")
    }
}

// 使用示例
class RequestProcessor @Inject constructor(
    cacheHandler: CacheHandler,
    networkHandler: NetworkHandler,
    errorHandler: ErrorHandler
) {
    private val chain = cacheHandler.apply {
        setNext(networkHandler).setNext(errorHandler)
    }
    
    suspend fun process(request: Request): Response {
        return chain.handle(request) ?: Response.Error("Unknown error")
    }
}

架构设计最佳实践

graph TB
    A[架构设计最佳实践] --> B[模块化设计]
    A --> C[依赖注入]
    A --> D[响应式编程]
    
    B --> E[功能模块]
    B --> F[基础设施模块]
    B --> G[业务模块]
    
    C --> H[Hilt/Dagger]
    C --> I[构造注入]
    C --> J[模块注入]
    
    D --> K[Flow]
    D --> L[LiveData]
    D --> M[RxJava]

架构设计原则总结

graph TB
    A[架构设计原则] --> B[可测试性]
    A --> C[可维护性]
    A --> D[可扩展性]
    
    B --> E[依赖注入]
    B --> F[单元测试]
    
    C --> G[模块化]
    C --> H[代码规范]
    
    D --> I[抽象接口]
    D --> J[设计模式]
    
    J --> K[创建型模式]
    J --> L[结构型模式]
    J --> M[行为型模式]

设计模式使用建议:

  1. 合理使用

    • 不要为了使用设计模式而使用设计模式
    • 根据实际业务需求选择合适的模式
  2. 性能考虑

    • 评估设计模式对性能的影响
    • 在关键路径上避免过度抽象
  3. 可维护性

    • 保持代码的清晰和简单
    • 添加适当的文档和注释
  4. 测试友好

    • 设计时考虑单元测试的便利性
    • 使用依赖注入便于mock
  5. 团队协作

    • 确保团队成员都理解所使用的设计模式
    • 建立统一的代码规范和架构标准

这些设计模式的实现需要考虑:

  • 内存使用
  • 启动性能
  • 代码复杂度
  • 团队理解成本
  • 后期维护难度

在实际项目中,应该根据项目规模、团队水平和业务需求来选择合适的设计模式组合。同时要注意避免过度设计,保持代码的简洁性和可维护性。