Извините за мой английский. Теперь я попытался реализовать шаблон стратегии.
ObjectBase.h
#pragma once
#include "canFill.h"
class ObjectBase
{
public:
ObjectBase();
virtual ~ObjectBase();
void fill(unsigned int value);
void setOilValue(unsigned int value);
protected:
std::unique_ptr<IFilliable> filliableBehavior;
private:
unsigned int oilValue;
};
ObjectBase.cpp
#include "ObjectBase.h"
ObjectBase::ObjectBase()
{
filliableBehavior = std::make_unique<CanFill>();
}
ObjectBase::~ObjectBase()
{
}
void ObjectBase::fill(unsigned int value)
{
filliableBehavior->fill(value); // should I also pass this here or I shouldn't use this pattern?
}
car.h
#pragma once
#include "ObjectBase.h"
class Car : public ObjectBase
{
public:
Car();
};
ElectricCar.h
#pragma once
#include "ObjectBase.h"
class ElectricCar : public ObjectBase
{
public:
ElectricCar();
~ElectricCar();
};
ElectricCar.cpp
#include "electriccar.h"
#include "cantFill.h"
ElectricCar::ElectricCar()
{
filliableBehavior = std::make_unique<CantFill>();
}
ElectricCar::~ElectricCar()
{
}
IFilliable.h
#pragma once
class IFilliable
{
public:
virtual ~IFilliable() {}
virtual void fill(unsigned int fillValue) = 0;
};
#endif // IFilliable_H
canFill.h
#pragma once
#include "IFilliable.h"
// Implementation of IMoveable Interface
class CanFill : public IFilliable
{
public:
CanFill() {}
~CanFill() {}
void fill(unsigned int fillValue);
};
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
#pragma once
#include "IFilliable.h"
class CantFill: public IFilliable
{
public:
CantFill() {}
~CantFill() {}
void fill(unsigned int fillValue);
};
cantFill.cpp
#include "cantFill.h"
#include <iostream>
void CantFill::fill(unsigned int fillValue)
{
std::cout << "this object can't be filled " << fillValue << std::endl;
}
Но есть вопрос,Например: если нужно изменить некоторые поля в классе ObjectBase из функции стратегии, я должен передать указатель на функцию стратегии, когда я вызываю ее из базового класса, или мне не следует использовать этот шаблон?