Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
111 lines (88 sloc) 4.62 KB
// Prototype.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <memory>
#include <map>
/*BasePrototype*/
class ICreature
{
public:
virtual void Action() = 0;
virtual std::unique_ptr<ICreature> Clone() const = 0;
};
/*Prototype1*/
class Monster : public ICreature
{
std::string name;
int health;
public:
Monster( std::string name, int health ) : name( name ), health( health ) {}
void Action() override
{
health--;
std::cout << name << " health: " << health << std::endl;
}
std::unique_ptr<ICreature> Clone() const override
{
return std::make_unique<Monster>( *this );
}
};
/*Prototype2*/
class Bird : public ICreature
{
std::string name;
int speed;
public:
Bird( std::string name, int speed ) : name(name), speed( speed ) {}
void Action() override
{
speed++;
std::cout<<name<<" speed: "<<speed<<std::endl;
}
std::unique_ptr<ICreature> Clone() const override
{
return std::make_unique<Bird>( *this );
}
};
/*Keys for prototypes to clone*/
enum{
SLOW_BIRD,
FAST_BIRD,
MONSTER
};
/*Prototype Registry*/
class CreatureRegistry
{
std::map<int, std::unique_ptr<ICreature>> cached_creatures;
public:
template<class _Ty, class... _Types>
void AddPrototype( int key, _Types&&... _Args)
{
cached_creatures[key] = std::make_unique<_Ty>( std::forward<_Types>( _Args )... );
}
std::unique_ptr<ICreature> Clone( const int key )
{
if ( cached_creatures.find( key ) == cached_creatures.end() )
return NULL;
return cached_creatures[key]->Clone();
}
};
int main()
{
CreatureRegistry creaturesCache;
creaturesCache.AddPrototype<Bird>( SLOW_BIRD, "Slow bird", 10);
creaturesCache.AddPrototype<Bird>( FAST_BIRD, "Fast bird", 100 );
creaturesCache.AddPrototype<Monster>( MONSTER, "Monster", 50 );
std::unique_ptr<ICreature> slowBird1 = creaturesCache.Clone( SLOW_BIRD );
std::unique_ptr<ICreature> slowBird2 = creaturesCache.Clone( SLOW_BIRD );
std::unique_ptr<ICreature> fastBird = creaturesCache.Clone( FAST_BIRD );
std::unique_ptr<ICreature> monster = creaturesCache.Clone( MONSTER );
slowBird1->Action();
slowBird1->Action();
slowBird2->Action();
fastBird->Action();
monster->Action();
std::cin.get();
}
You can’t perform that action at this time.