问题
This is a followup to this question.
Basically I want a container that stores objects and later does something with them. I want to put both, the action performed on the objects (ActionPolicy
), and the storage (StoragePolicy
), into policy classes. At the end, there should be two functions on the class:
addObject()
with a signature depending onActionPolicy
, i.e. this function should be defined in there.execute()
, which goes over all of the objects stored byStoragePolicy
and executesActionPolicy::evaluate(obj)
on all of them.
In (partially pseudo-)code (the places marked with Here
are the ones that don't work in this design):
struct ActionPolicy {
// Signature is dependant on this policy
void addObject(T obj, /* ... */) {
// Do something with the object
StoragePolicy::store(obj); // <--- Here
}
void eval(T obj) {
// Do something with the object
}
};
struct StoragePolicySingle {
T obj;
void store(T obj) {
this->obj = obj;
}
void execute() {
ActionPolicy::execute(obj); // <--- Here
}
};
struct StoragePolicyMulti {
std::vector<T> vec;
void store(T obj) {
vec.push_back(obj´);
}
void execute() {
for (obj in vec) {
ActionPolicy::execute(obj); // <--- Here
}
}
};
template <class A, class B> MyClass : public A, public B {
// ...
};
All of this is performance-critical, so I can't just use a vector with one entry instead of StoragePolicySingle
.
How would you solve this? Any pattern I'm missing?
回答1:
Why does ActionPolicy
need to know about StoragePolicy
?
Why does an ActionPolicy
have objects added to it?
If you pass the ActionPolicy
to the StoragePolicy
as an argument to execute
, then call eval
on either the single item or the collection, does this not solve it for you?
来源:https://stackoverflow.com/questions/8334926/c-policy-design-with-dependencies