gpt4 book ai didi

c++ - 在 C++ 中确保单个实例但不是全局实例的最佳方法

转载 作者:行者123 更新时间:2023-11-30 02:27:03 25 4
gpt4 key购买 nike

我正在开发一个类来控制网络适配器,我需要确保只有一个此类实例。全局访问不是必需的,因为此类仅由执行网络操作的客户端使用,所以我认为单例模式并非如此。

目前我有一个工厂,它有一个这个 netAdapter 的静态实例,但我不确定这是一个好的解决方案。

执行此操作并避免可测试性问题的最佳方法是什么?

编辑:我有多个适配器(wifi、以太网、2G/3G/4G),但每个适配器只能有一个实例。

最佳答案

I need to ensure that there's only a single instance of this class.

... so I think that's not the case for the singleton pattern.

将类限制为单个实例正是单例模式的定义。

What's the best way to do this and avoid testability problems?

如果将类限制为单个实例,我认为无法避免可测试性问题。最好的方法可能是忘记这样的要求。

Global access isn't necessary

然后我建议一个局部静态变量:

void function_that_needs_a_single_instance_ever() {
static singleton_class instance;
// do something with your singleton
}

关于c++ - 在 C++ 中确保单个实例但不是全局实例的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com