我已经实现了两种我认为应该如何实现单例类的方法,我只是想听听程序员的意见,哪一种是最好的方法。
每个方法都使用这些类:
class Animal {
public:
virtual void speak() const = 0;
};
class Dog {
virtual void speak() { cout << "Woof!!"; }
};
第一种方法:
class AnimalFactory {
public:
static Animal* CreateInstance(int theTypeOfAnimal);
private:
AnimalFactory() { };
static int count; // this will be used to count the number of objects created
static int maxCount; // this is the max count allowed.
};
int AnimalFactory::count = 0;
int AnimalFactory::maxCount = 1;
Animal* AnimalFactory::CreateInstance(int theTypeOfAnimal)
{
Animal* pAnimal = NULL;
if(pAnimal != NULL)
{
return pAnimal;
}
switch(theTypeOfAnimal)
{
case 0:
pAnimal = new Dog();
count++;
break;
case 1:
pAnimal = new Cat();
count++;
break;
case 2:
pAnimal = new Spider();
count++;
break;
default:
cout << "Not known option";
}
return pAnimal;
}
第二种方法:
template<typename classType>
class Singleton {
public:
classType& instance()
{
static classType object;
return object;
}
};
任何意见将不胜感激,谢谢:)!
最佳答案
在大多数情况下,Singleton 是被滥用的。一般的建议是:不要使用它!如果您认为您确实遇到了单例是正确解决方案的情况:概率仍然对您不利。如果您真的非常确定需要使用 Singleton,您可能仍想将其用作某种美化数据:不要。它会伤害你。
好的,您已收到警告。
第二种方法在 C++ 2011 中具有明显的优势,即它是线程安全的。它也恰好更简单。
如果您受困于尚未实现 C++ 2011 逻辑的编译器,并且在多线程应用程序中使用单例,则需要确保它仅被初始化一次,即使访问函数是从两个线程同时调用。当然,这会导致其他一些不起作用的事情:不要使用双重检查锁定模式。它[也]不起作用。如果您实现了它,就会有人来“修复”您的代码。
关于c++ - 单例类 - 哪个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129637/