vendredi 4 octobre 2019

Strategy pattern and editing base class fields in strategy

Sorry for my english. Now I tried to implement the strategy pattern.

ObjectBase.h

#ifndef ObjectBase_H
#define ObjectBase_H

#include "canFill.h"
class ObjectBase
{
public:
    ObjectBase();
    virtual ~ObjectBase();
    void fill(unsigned int value);
protected:
    IFilliable *moveableBehavior;
private:
    unsigned int oilValue;
};

#endif // ObjectBase_H

ObjectBase.cpp

#include "ObjectBase.h"

ObjectBase::ObjectBase()
{
    moveableBehavior = new CanFill();
}
ObjectBase::~ObjectBase()
{
    delete moveableBehavior;
}
void ObjectBase::fill(unsigned int value)
{
    moveableBehavior->fill(value); // should I also pass this here or I shouldn't use this pattern?
}

car.h

#ifndef CAR_H
#define CAR_H

#include "ObjectBase.h"
class Car : public ObjectBase
{
public:
    Car();
};

#endif // CAR_H

ElectricCar.h

#ifndef ELECTRICCAR_H
#define ELECTRICCAR_H
#include "ObjectBase.h"

class ElectricCar : public ObjectBase
{
public:
    ElectricCar();
};

#endif // ELECTRICCAR_H

ElectricCar.cpp

#include "electriccar.h"
#include "cantFill.h"

ElectricCar::ElectricCar()
{
    moveableBehavior = new CantFill();
}

IFilliable.h

#ifndef IMOVEABLE_H
#define IMOVEABLE_H

class IFilliable
{
public:
    virtual ~IFilliable() {}
    virtual void fill(unsigned int fillValue) = 0;
};


#endif // IMOVEABLE_H

canFill.h

#ifndef MOVE_H
#define MOVE_H
#include "IFilliable.h"

// Implementation of IMoveable Interface
class CanFill : public IFilliable
{
public:
    CanFill() {}
    ~CanFill() {}
    void fill(unsigned int fillValue);
};

#endif // MOVE_H

canFill.cpp

#include "canFill.h"
#include <iostream>

void CanFill::fill(unsigned int fillValue)
{
    std::cout << "filled:" << fillValue << std::endl;
    // change oilValue of the base class here
}

cantFill.h

#ifndef CANTMOVE_H
#define CANTMOVE_H
#include "IFilliable.h"

class CantFill: public IFilliable
{
public:
    CantFill() {}
    ~CantFill() {}
    void fill(unsigned int fillValue);
};


#endif // CANTMOVE_H

cantFill.cpp

#include "cantFill.h"
#include <iostream>

void CantFill::fill(unsigned int fillValue)
{
    std::cout << "this object can't be filled " << fillValue << std::endl;
}

But there is a question. For example: if a need to change some fields in the ObjectBase class from strategy function, must I pass a pointer to the strategy function when I call it from the base class or I shouldn't use this pattern?

Aucun commentaire:

Enregistrer un commentaire