You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在子类Bweb中调用Aimp实现的firstMethod(禁用mixin)

问题代码整理

抽象类A:

abstract class A {
    Future<String> firstMethod();
}

A的实现类:

class Aimp implements A {
  @override
  Future<String> firstMethod() async {
      return "test";
  }
}

继承自A的抽象类B:

abstract class B extends A {
    Future<String> secondMethod();
}

B的实现类Bweb:

class Bweb extends B {
    @override
      Future<Object> secondMethod() async {
          final t = //我想调用firstMethod()
         if(t.isNotEmpty()) // 执行操作
    }
}

解决方案(不使用mixin)

因为B继承自A,Bweb作为B的实现类必须重写firstMethod,以下几种方式可以调用Aimp中的firstMethod实现:

方案1:直接实例化Aimp调用

直接在secondMethod中创建Aimp实例并调用方法,同时在firstMethod中复用该实现:

class Bweb extends B {
    @override
    Future<Object> secondMethod() async {
        final aInstance = Aimp();
        final t = await aInstance.firstMethod();
        if(t.isNotEmpty) {
            // 执行你的操作
        }
        return ""; // 按需求返回对应类型的值
    }

    @override
    Future<String> firstMethod() async {
        return Aimp().firstMethod();
    }
}

方案2:依赖注入传入A实例

通过构造函数传入A的实例,后续可灵活替换实现类,无需修改Bweb内部逻辑:

class Bweb extends B {
    final A aInstance;

    Bweb(this.aInstance);

    @override
    Future<Object> secondMethod() async {
        final t = await aInstance.firstMethod();
        if(t.isNotEmpty) {
            // 执行你的操作
        }
        return "";
    }

    @override
    Future<String> firstMethod() async {
        return aInstance.firstMethod();
    }
}

// 使用示例
final bWeb = Bweb(Aimp());

方案3:类内持有Aimp实例委托实现

在Bweb内部维护一个Aimp实例,统一委托调用:

class Bweb extends B {
    final Aimp _aImp = Aimp();

    @override
    Future<Object> secondMethod() async {
        final t = await _aImp.firstMethod();
        if(t.isNotEmpty) {
            // 执行你的操作
        }
        return "";
    }

    @override
    Future<String> firstMethod() async {
        return _aImp.firstMethod();
    }
}

内容的提问来源于stack exchange,提问作者Cyrus the Great

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:02:28