lundi 15 janvier 2018

Abstract Factory c++

I'm trying to understand the abstract factory pattern, here is my first approximation,

#include <iostream>
using namespace std;

class Soldier
{
    public:
    virtual void shoot()=0;
};

class Archer: public Soldier
{
    public:
    void shoot(){
        cout<<"Archer shoot"<<endl;
    }
};

class Rider: public Soldier
{
    public:
    void shoot(){
        cout<<"Rider shoot"<<endl;
    }
};

class AbstractFactory
{
    public:
    virtual Soldier* createArcher()=0;
    virtual Soldier* createRider()=0;
};

class OrcFactory: public AbstractFactory
{
    Soldier* createArcher()
    {
        return new Archer();
    };
    Soldier* createRider()
    {
        return new Rider();
    };
};

class HumanFactory: public AbstractFactory
{
    Soldier* createArcher()
    {
        return new Archer();
    };
    Soldier* createRider()
    {
        return new Rider();
    };
};

class Game
{

    public:
    AbstractFactory* factory;
    Game(AbstractFactory* factory):factory(factory){};
};

int main()
{
    Game* game = new Game(new HumanFactory);
    Archer* HumanArcher = static_cast <Archer*>(game->factory->createArcher());
    Rider* humanRider = static_cast <Rider*>(game->factory->createRider());
    HumanArcher->shoot();
    humanRider->shoot();
    return 0;
}

this is what I want to reproduce,

enter image description here

I have experience programing but I'm newbie with patterns, not sure if this is the optimal solution or eve if it's a good solution :/.

I'm reading about game engine architecture, but I'm stuck in this, not by errors, just doubt about the right solution for this exercise, the book have basic examples but not enough to understand it at all.

(yes, i have searched in other sites, got some solutions but not sure about this one)

Any comments? thanks for your time guys.

Aucun commentaire:

Enregistrer un commentaire