Singleton クラスをどのように実装すべきかについて、私は 2 つの方法を実装しました。どちらを使用するのが最適な方法であるかについて、プログラマーの意見を求めたいだけです。
各メソッドは次のクラスを使用します。
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;
}
2 番目の方法:
template<typename classType>
class Singleton {
public:
classType& instance()
{
static classType object;
return object;
}
};
どんな意見でも感謝します、ありがとう:)!