当前位置: 首页 > news >正文

ServiceLibrary 库使用演示

1. 项目背景介绍

1.1 面临的问题

// 传统方式:模块间直接依赖class LoginActivity {fun onLoginSuccess() {// 直接依赖具体Activity,编译时耦合val intent = Intent(this, UserActivity::class.java)startActivity(intent)}}// 问题:// 1. 模块间编译时耦合// 2. 难以进行单元测试// 3. 多应用构建困难// 4. 团队协作冲突

1.2 解决方案

 

// 使用ServiceLibrary:通过接口和服务定位器解耦class LoginActivity {private val userService: UserService by lazy {getService<UserService>()}fun onLoginSuccess() {// 通过服务接口跳转,完全解耦userService.toUserPage(this)}}

2. 库的核心组件演示

2.1 服务定位器演示

 

// 1. 定义服务接口interface UserService {fun toUserPage(context: Context, userId: String? = null)fun getUserInfo(userId: String): AccountInfo?}// 2. 实现服务class UserServiceImpl : UserService {override fun toUserPage(context: Context, userId: String?) {val params = userId?.let { mapOf("userId" to it) }ServiceManager.navigate("/user", context, params)}override fun getUserInfo(userId: String): AccountInfo? {return AccountManager.getAccount()}}// 3. 注册服务class UserModule : BaseServiceModule() {override fun register(locator: ServiceProvider) {locator.register(UserService::class.java, UserServiceImpl())}}

2.2 路由系统演示

// 1. 注册路由ServiceManager.registerRoute("/user", UserActivity::class.java)ServiceManager.registerRoute("/login", LoginActivity::class.java)ServiceManager.registerRoute("/home", HomeActivity::class.java)// 2. 路由跳转ServiceManager.navigate("/user", context, mapOf("userId" to "123"))// 3. 拦截器class LoginInterceptor : RouterInterceptor {override fun intercept(context: Context, route: String, params: Map<String, Any>?): Boolean {val needLoginRoutes = listOf("/user", "/profile")if (needLoginRoutes.contains(route)) {val token = TokenManager.getToken()if (token.isNullOrEmpty()) {ServiceManager.navigate("/login", context)return true // 拦截}}return false // 不拦截}}

 

3. 完整使用示例

3.1 应用初始化

class MyApplication : Application() {override fun onCreate() {super.onCreate()// 注册服务模块ServiceManager.registerModule(UserModule())ServiceManager.registerModule(LoginModule())// 注册路由ServiceManager.registerRoute("/user", UserActivity::class.java)ServiceManager.registerRoute("/login", LoginActivity::class.java)ServiceManager.registerRoute("/home", HomeActivity::class.java)// 添加拦截器RouterManager.addInterceptor(LoginInterceptor())// 初始化ServiceManager.initialize()}}

 

3.2 登录模块演示

 

// 登录服务接口interface LoginService {fun toLoginPage(context: Context)fun toRegisterPage(context: Context)suspend fun login(username: String, password: String): BaseResponse<User>}// 登录服务实现class LoginServiceImpl : LoginService {override fun toLoginPage(context: Context) {ServiceManager.navigate("/login", context)}override fun toRegisterPage(context: Context) {ServiceManager.navigate("/register", context)}override suspend fun login(username: String, password: String): BaseResponse<User> {val networkService = getService<NetworkService>()return networkService.request {apiLoginInterface.login(LoginRequest(username, password))}}}// 登录Activityclass LoginActivity : AppCompatActivity() {private val userService: UserService by lazy {getService<UserService>()}private val loginService: LoginService by lazy {getService<LoginService>()}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_login)initListener()}private fun initListener() {// 注册按钮findViewById<Button>(R.id.btnRegister).setOnClickListener {loginService.toRegisterPage(this)}// 登录按钮findViewById<Button>(R.id.btnLogin).setOnClickListener {performLogin()}}private fun performLogin() {val username = findViewById<EditText>(R.id.etUsername).text.toString()val password = findViewById<EditText>(R.id.etPassword).text.toString()lifecycleScope.launch {try {val result = loginService.login(username, password)if (result.isSuccess()) {// 登录成功,跳转到用户页面userService.toUserPage(this@LoginActivity)} else {Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()}} catch (e: Exception) {Toast.makeText(this@LoginActivity, "网络错误", Toast.LENGTH_SHORT).show()}}}}

3.3 用户模块演示

 

// 用户Activityclass UserActivity : RouterActivity() {private val userService: UserService by lazy {getService<UserService>()}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_user)// 获取路由参数val userId = getRouteParamString("userId")if (userId != null) {loadUserInfo(userId)}initListener()}private fun initListener() {// 用户设置按钮findViewById<Button>(R.id.btnSettings).setOnClickListener {userService.toUserSettings(this)}// 用户资料按钮findViewById<Button>(R.id.btnProfile).setOnClickListener {val userId = getRouteParamString("userId") ?: "default"userService.toUserProfile(this, userId)}}private fun loadUserInfo(userId: String) {lifecycleScope.launch {val userInfo = userService.getUserInfo(userId)userInfo?.let { displayUserInfo(it) }}}private fun displayUserInfo(userInfo: AccountInfo) {findViewById<TextView>(R.id.tvUserName).text = userInfo.getName()findViewById<TextView>(R.id.tvUserEmail).text = userInfo.getEmail()}}

4. 多应用构建演示

4.1 应用A:标准版

 

// 应用A的Applicationclass AppA : Application() {override fun onCreate() {super.onCreate()// 注册标准模块ServiceManager.registerModule(UserModule())ServiceManager.registerModule(LoginModule())// 注册标准路由ServiceManager.registerRoute("/user", UserActivity::class.java)ServiceManager.registerRoute("/login", LoginActivity::class.java)ServiceManager.initialize()}}

4.2 应用B:定制版

 

// 应用B的Applicationclass AppB : Application() {override fun onCreate() {super.onCreate()// 注册定制模块ServiceManager.registerModule(CustomUserModule())ServiceManager.registerModule(LoginModule())// 注册定制路由ServiceManager.registerRoute("/user", CustomUserActivity::class.java)ServiceManager.registerRoute("/login", CustomLoginActivity::class.java)ServiceManager.initialize()}}// 定制用户模块class CustomUserModule : BaseServiceModule() {override fun register(locator: ServiceProvider) {locator.register(UserService::class.java, CustomUserServiceImpl())}}// 定制用户服务实现class CustomUserServiceImpl : UserService {override fun toUserPage(context: Context, userId: String?) {// 定制逻辑:添加VIP标识val params = userId?.let { mapOf("userId" to it, "isVip" to true) }ServiceManager.navigate("/user", context, params)}override fun getUserInfo(userId: String): AccountInfo? {// 定制逻辑:返回VIP用户信息return CustomAccountManager.getVipAccount()}}

5. 单元测试演示

5.1 服务测试

class UserServiceTest {@Testfun `test user service navigation`() {// 准备测试环境ServiceManager.reset()ServiceManager.registerModule(UserModule())ServiceManager.initialize()val userService = ServiceManager.getService(UserService::class.java)// 测试页面跳转val mockContext = mock<Context>()userService.toUserPage(mockContext, "123")// 验证路由调用verify(mockContext).startActivity(any())}@Testfun `test user service with mock`() {// 使用Mock服务val mockUserService = mock<UserService>()ServiceManager.registerService(UserService::class.java, mockUserService)val userService = ServiceManager.getService(UserService::class.java)// 测试业务逻辑whenever(mockUserService.getUserInfo("123")).thenReturn(AccountInfo("test"))val result = userService.getUserInfo("123")assertEquals("test", result?.getName())}}

 

5.2 路由测试

class RouterTest {@Testfun `test route registration and navigation`() {// 重置路由RouterManager.clear()// 注册路由RouterManager.register("/test", TestActivity::class.java)// 测试导航val mockContext = mock<Context>()RouterManager.navigate(mockContext, "/test", mapOf("param" to "value"))// 验证Intent创建verify(mockContext).startActivity(any())}@Testfun `test route interceptor`() {// 重置路由RouterManager.clear()// 添加拦截器val mockInterceptor = mock<RouterInterceptor>()whenever(mockInterceptor.intercept(any(), any(), any())).thenReturn(true)RouterManager.addInterceptor(mockInterceptor)// 测试拦截val mockContext = mock<Context>()RouterManager.navigate(mockContext, "/test")// 验证拦截器被调用verify(mockInterceptor).intercept(any(), any(), any())}}

 

6. 性能对比演示

6.1 传统方式 vs ServiceLibrary

// 传统方式:编译时耦合class TraditionalLoginActivity {fun onLoginSuccess() {// 直接依赖,编译时耦合val intent = Intent(this, UserActivity::class.java)intent.putExtra("userId", "123")startActivity(intent)}}// ServiceLibrary方式:运行时解耦class ModernLoginActivity {private val userService: UserService by lazy {getService<UserService>()}fun onLoginSuccess() {// 通过接口,运行时解耦userService.toUserPage(this, "123")}}// 性能对比结果:// 编译时间:传统方式更快(直接引用)// 运行时间:ServiceLibrary稍慢(反射查找)// 内存占用:基本相同// 可维护性:ServiceLibrary显著更好

 

7. 实际项目收益演示

7.1 模块解耦效果

// 模块A:登录模块class LoginModule : BaseServiceModule() {override fun register(locator: ServiceProvider) {locator.register(LoginService::class.java, LoginServiceImpl())}}// 模块B:用户模块class UserModule : BaseServiceModule() {override fun register(locator: ServiceProvider) {locator.register(UserService::class.java, UserServiceImpl())}}// 模块C:支付模块class PaymentModule : BaseServiceModule() {override fun register(locator: ServiceProvider) {locator.register(PaymentService::class.java, PaymentServiceImpl())}}// 各模块独立开发,通过接口通信// 修改一个模块不影响其他模块// 可以独立测试每个模块

 

7.2 团队协作效果

 

// 团队A:负责登录模块

// 只需要实现LoginService接口,不需要知道其他模块的实现

// 团队B:负责用户模块  

// 只需要实现UserService接口,不需要知道其他模块的实现

// 团队C:负责支付模块

// 只需要实现PaymentService接口,不需要知道其他模块的实现

// 接口契约由架构团队统一管理

// 各团队可以并行开发

// 减少代码冲突

8. 总结

8.1 核心价值体现

 

// 1. 模块解耦// 传统:LoginActivity → UserActivity (编译时依赖)// 现在:LoginActivity → UserService → UserActivity (运行时解耦)// 2. 统一管理// 服务注册、获取、路由跳转统一管理ServiceManager.registerModule(UserModule())ServiceManager.registerRoute("/user", UserActivity::class.java)// 3. 多应用支持// 同一套代码,不同应用可以有不同的实现AppA: UserActivityAppB: CustomUserActivity// 4. 易于测试// 可以轻松替换服务实现进行单元测试ServiceManager.registerService(UserService::class.java, MockUserServiceImpl())

8.2 技术分享要点

  • 问题驱动:从实际项目痛点出发
  • 方案对比:传统方式 vs ServiceLibrary方式
  • 代码演示:完整的实际使用示例
  • 效果验证:性能对比、团队协作效果
  • 最佳实践:模块设计、测试策略
http://www.dtcms.com/a/279424.html

相关文章:

  • [AI8051U入门第一步]环境安装和按键控制流水灯
  • 将dist文件打包成exe可执行程序
  • MySQL服务故障分析报告​​
  • 以楼宇自控系统为抓手,实现人居环境优化与建筑能效跃升
  • 职业教育领域的“101计划
  • keepalive模拟操作部署
  • 学习日志09 python
  • 【SVN】SVN 客户端的安装与操作
  • 设计模式之代理模式:掌控对象访问的优雅之道
  • CVE-2017-7525源码分析与漏洞复现(Jackson 反序列化)
  • Android 中 实现格式化字符串
  • vue2/3生命周期使用建议
  • TCL在芯片设计与验证中的应用实践
  • WinUI3开发_Combobox实现未展开时是图标下拉菜单带图标+文字
  • ConcurrentHashMap 原子操作详解:computeIfAbsent、computeIfPresent和putIfAbsent
  • 技术人生——第12集:思想为王,功能在后
  • (5)LangGraph4j框架ReActAgent实现
  • mit6.5840-lab4C-Snapshot-25Summer
  • Java Stream流详解
  • 文心一言 4.5 开源深度剖析:中文霸主登场,开源引擎重塑大模型生态
  • C++11 std::is_permutation:从用法到原理的深度解析
  • 什么是延迟双删
  • 算法训练营day18 530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236. 二叉树的最近公共祖先
  • 通过 ip a 查看网络接口名
  • 【算法】贪心算法:摆动序列C++
  • 2025js——面试题(8)-http
  • Linux 系统下的 Sangfor VDI 客户端安装与登录完全攻略 (CentOS、Ubuntu、麒麟全线通用)
  • 程序跑飞是什么?
  • 核电概念盘中异动,中核科技涨停引领板块热度
  • 物联网技术促进能量收集创新应用落地