#include <iostream>
enumclass KObjectType
{
KPlayerType,
kMonsterType,
kNPCType,
KObjectTypeCount,
};
class Node
{
public:
virtual void setType(KObjectType type) = 0;
virtual KObjectType getType()const = 0;
virtual ~Node(){};
virtual void showType() {};
};
class Player :public Node
{
public:
virtual void setType(KObjectType type) override;
virtual KObjectType getType()const override;
virtual void showType() override {std::cout <<" PlayerType" << std::endl;};
private:
KObjectType m_enType_;
};
voidPlayer::setType(KObjectType type)
{
m_enType_ = type;
}
KObjectType Player::getType()const
{
returnm_enType_;
}
class Monster :public Node
{
public:
virtual void setType(KObjectType type) override;
virtual KObjectType getType()const override;
virtual void showType() override {std::cout <<" MonsterType" << std::endl;};
private:
KObjectType m_enType_;
};
void Monster::setType(KObjectType type)
{
m_enType_ = type;
}
KObjectType Monster::getType()const
{
returnm_enType_;
}
class FactoryCreation
{
public:
static Node* create(KObjectType type);
};
Node* FactoryCreation::create(KObjectType type)
{
Node *object = nullptr;
switch (type) {
case KObjectType::KPlayerType:
object =new Player();
break;
case KObjectType::kMonsterType:
object =new Monster();
break;
default:
break;
}
if (object) {
object->setType(type);
}
return object;
}
int main()
{
auto p =FactoryCreation::create(KObjectType::KPlayerType);
p->showType();
delete p;
auto m =FactoryCreation::create(KObjectType::kMonsterType);
m->showType();
delete m;
return 0;
}
结果输出如下:
PlayerType
MonsterType
Program ended with exit code: 0