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

如何用单个变量适配多个具备相同API的类?

解决方案:用多态+基类指针/智能指针实现单变量复用

核心思路

利用多态特性,用基类的指针(或智能指针)指向子类对象,只维护一个基类类型的变量,在用户选择时动态绑定到对应的子类实例,后续直接通过这个变量调用统一的start()/stop()接口即可,完全符合你“仅在选择时分支一次”的需求。

C++ 实现示例

  1. 定义抽象基类(规定统一接口)
class Base {
public:
    virtual void start() = 0; // 纯虚函数,强制子类实现
    virtual void stop() = 0;
    virtual ~Base() = default; // 虚析构,避免子类对象内存泄漏
};
  1. 子类继承并实现具体逻辑
class A : public Base {
public:
    void start() override {
        // 这里写A类start的具体逻辑
    }
    void stop() override {
        // 这里写A类stop的具体逻辑
    }
};

class B : public Base {
public:
    void start() override {
        // 这里写B类start的具体逻辑
    }
    void stop() override {
        // 这里写B类stop的具体逻辑
    }
};
  1. 主逻辑(单变量复用)
#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<Base> myVar; // 单个基类智能指针,自动管理内存
    int userChoice;

    while (true) {
        // 获取用户选择
        std::cout << "选择类(1:A, 2:B, 0:退出): ";
        std::cin >> userChoice;

        if (userChoice == 0) break;

        // 仅在选择时分支,绑定对应子类实例
        if (userChoice == 1) {
            myVar = std::make_unique<A>();
        } else if (userChoice == 2) {
            myVar = std::make_unique<B>();
        } else {
            std::cout << "无效选择,请重新输入" << std::endl;
            continue;
        }

        // 后续无需分支,直接调用统一接口
        myVar->start();

        // 模拟后续操作,比如等待用户触发stop
        std::cout << "按任意键执行stop..." << std::endl;
        std::cin.get();
        std::cin.get(); // 处理输入残留的换行符

        myVar->stop();
    }

    return 0;
}

Python 实现示例(动态类型更简洁)

Python是动态类型语言,不需要显式定义抽象基类也能实现,当然定义基类做约束也可以:

class Base:
    def start(self):
        raise NotImplementedError("子类必须实现start方法")
    def stop(self):
        raise NotImplementedError("子类必须实现stop方法")

class A(Base):
    def start(self):
        print("A类启动")
    def stop(self):
        print("A类停止")

class B(Base):
    def start(self):
        print("B类启动")
    def stop(self):
        print("B类停止")

def main():
    myVar = None
    while True:
        user_choice = input("选择类(1:A, 2:B, 0:退出): ")
        if user_choice == '0':
            break
        
        # 仅在选择时分支
        if user_choice == '1':
            myVar = A()
        elif user_choice == '2':
            myVar = B()
        else:
            print("无效选择,请重新输入")
            continue
        
        # 直接调用统一接口
        myVar.start()
        input("按任意键执行stop...")
        myVar.stop()

if __name__ == "__main__":
    main()

方案优势

  • 全程只用一个变量myVar,仅在用户选择时做一次分支判断,后续代码完全复用
  • 新增子类时,只需继承基类实现接口,主逻辑仅需增加一个分支判断,扩展性极强
  • C++用智能指针自动管理内存,无需手动释放,避免内存泄漏问题

内容的提问来源于stack exchange,提问作者Fernando Chu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 17:25:59