首页 > 解决方案 > 将服务级别缩小到更小部分的最佳方法

问题描述

目前正在用 Flutter 制作一个大型应用程序,我被困在服务类的架构上。firestore CRUD 操作有一个服务类。这个类有很多方法,我想把它分成小块。我使用抽象类来保护方法。我找到了一种使用 mixins 的方法,但不知道它是否好用。

https://gist.github.com/pMertDogan/fcd301d768f3980a898cec33a9acaa4f

//Extend CRUDSERVICE rules aka abstract class => Test
mixin Update{
  
  void updateSomething();
  
}

mixin Read{
  void readSomething();
}

//BASE class for CRUDSERVICE 
abstract class Test with Update,Read{
  doSomeCreateOP(String x);
}

//
class CrudService extends Test with UpdateService , ReadService{
  @override
  doSomeCreateOP(String x) {
    print('crated ' + x);
  }
    
      
      
    }
    
    mixin UpdateService{
    //   @override
      void updateSomething() {
       print('updated');
      }
    }
    
    mixin ReadService{
    //   @override
      void readSomething() {
       print('read');
      }
    }
    
    
    void main() {
      CrudService croudService = CrudService();
      croudService.doSomeCreateOP(' dartSide');
      croudService.updateSomething();
      croudService.readSomething();
    }

CreateService 和 UpdateService mixin 只是示例。我想如果我需要更新用户信息,所有方法都由 UserServiceMix mixin 处理,如果它是 Friend 然后它由 FriendServiceMix 处理,所以我可以像基于域一样拆分它们。每个 mixin 负责特定操作。然后我可以在 mixin 的帮助下管理独立文件并对其进行汇总。

这是好方法吗?

标签: flutterdart

解决方案


我相信这是一个很好的方法。这是一种相当灵活的方法。我们也将它用于 API 版本控制。

abstract class Service {
  void method1();
  void method2();
}

mixin Method1V1 {
  void method1() {
    print("method1");
  }
}

mixin Method2V1 {
  void method2() {
    print("method2");
  }
}

mixin Method2V2 {
  void method2() {
    print("method2 with changed logic");
  }
}

class ServiceV1 extends Service with Method1V1, Method2V1 {

}

class ServiceV2 extends Service with Method1V1, Method2V2 {

}

void main() {
  final version = 2;

  final Service service = version == 1 ? ServiceV1() : ServiceV2();

  service.method2();
}

推荐阅读