不允许定义类的多个实例

Disallow defining more than one instance of a class

本文关键字:实例 定义 不允许      更新时间:2023-10-16

虽然以前我读到不允许定义一个对象的进一步实例。但我再也找不到那篇文章了。谁能告诉我如何防止从类CLog定义任何其他对象?

class CLog
{
........

} log;

单例的另一种解决方案是使用 Service Locator 模式。

http://gameprogrammingpatterns.com/service-locator.html 中描述了对它的良好描述以及如何使用它。

同样,像单例一样,这种模式应该谨慎使用,但是日志记录系统可能是一个很好的用例,如果没有别的,它会教你一些新的设计模式。

将构造函数设为私有。定义一个返回类实例的公共方法。

class sample{
 private:
    sample(){};
    static *sample instance;
public:
static *sample getInstance(){
   if (instance != null)
      instance = new sample();
   return instance;
}

getInstance() 方法在创建之前创建类实例,它会检查该实例是否存在,如果存在,它会重新调整现有的实例,否则会创建一个新的实例。通过这种方式,您可以使类创建类的单个实例。由于构造函数是私有的,因此没有人可以使用构造函数创建对象。

相关文章: