c++ - 跨平台代码组织

标签 c++ oop singleton

我有这个监视器类,它可以通过静态函数访问其自身的实例。当调用 GetMonitor 时,搜索 mMonitors 映射并返回实例,如果实例不存在,则创建它。

class Monitor {
    public:
        static Monitor& GetPrimaryMonitor();
        static Monitor& GetMonitor(int number = 0);
        int GetXResolution();
        int GetYResolution();
        void SetXResolution(int resolution);
        void SetYResolution(int resolution);

    protected:
    private:
        Monitor(int number);
        static std::map<int, Monitor*> mMonitors;
};

我的问题是,我应该什么时候删除映射中的 Monitor 实例?或者我应该采取不同的方法来允许用户创建他/她想要的任意数量的监视器实例吗?这似乎是错误的,因为这就好像他们要创建一个物理监视器,而我的方法允许访问已经可用的共享资源。提前致谢,嗯。

最佳答案

should I take a different approach of allowing the user to create as many monitor instances he/she wants? This seems wrong because it would be as if they would be creating a physical monitor whereas my approach gives access to shared resources already available

是的,你绝对应该。出于几个原因:

  • 您为用户提供了监视器的抽象概念,而不是真正的物理监视器。因此,拥有与实际物理监视器数量不同的 Monitor 对象不一定是错误的。
  • 不同的用户可能有不同数量的监视器
  • 人们可能有“虚拟”监视器,或者可能是用于测试的模拟实现,它们根本不对应于物理监视器。
  • 单例是just a plain horrible idea .

关于c++ - 跨平台代码组织,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7179312/

相关文章:

python - 从静态方法访问静态变量

javascript - 强制子类不可变

swift - 如何结合依赖注入(inject)使用单例模式?

单线程 Wcf 单例

C# - 为什么在引用类常量时执行流向实例变量?

c++ - 在 C++ 中将 int 转换为 bool[]

java - 为什么我们不在 getter 中使用 'this'?

c++ - C++中的线程安全

c++ - 打印unicode字符c++ linux

c++ - 为什么我在函数内部使用引用并通过引用返回它仍然有效?