I'll throw some code in your eyes first.
// Example program
#include <iostream>
#include <string>
#include <memory>
class Model
{
public:
virtual bool set(int p_attrId, int p_value) {return false;};
virtual bool get(int p_attrId, int & p_value) const {return false;};
};
class Derived1: public Model
{
static constexpr int c_classId = 1;
int value = 1;
public:
enum EAttrs
{
eAttr1 = c_classId * 1000
};
virtual bool set(int p_attrId, int p_value) override
{
switch(p_attrId)
{
case eAttr1:
value = p_value;
return true;
default:
return Model::set(p_attrId, p_value);
}
}
virtual bool get(int p_attrId, int & p_value) const override
{
switch(p_attrId)
{
case eAttr1:
p_value = value;
return true;
default:
return Model::get(p_attrId, p_value);
}
}
};
class Derived2: public Model
{
static constexpr int c_classId = 2;
int value = 2;
public:
enum EAttrs
{
eAttr1 = c_classId * 1000
};
virtual bool set(int p_attrId, int p_value) override
{
switch(p_attrId)
{
case eAttr1:
value = p_value;
return true;
default:
return Model::set(p_attrId, p_value);
}
}
virtual bool get(int p_attrId, int & p_value) const override
{
switch(p_attrId)
{
case eAttr1:
p_value = value;
return true;
default:
return Model::get(p_attrId, p_value);
}
}
};
void printInt(std::unique_ptr<Model> const & p_model, int p_attrId)
{
int value;
bool result = p_model->get(p_attrId, value);
if(!result)
{
std::cout << "Failed to get attribute " << p_attrId << "\n";
return;
}
std::cout << "AttrID: " << p_attrId << " Value: " << value << "\n";
}
int main()
{
std::unique_ptr<Model> derived1 (new Derived1);
std::unique_ptr<Model> derived2 (new Derived2);
printInt(derived1, Derived1::eAttr1);
printInt(derived2, Derived2::eAttr1);
}
The motivation behind this is acquisition of all data from a single interface.
The challenge with this design is that the Model interface needs to implement all types required from anywhere in the program.
How would you extend the types provided?
Is there some other design that could be used to achieve similar results?
Aucun commentaire:
Enregistrer un commentaire