C++具有依赖关系的策略设计
这是这个问题的后续。
基本上我想要一个容器来存储对象,然后用它们做一些事情。我想将对对象执行的操作 (ActionPolicy
) 和存储 (StoragePolicy
) 放入策略类中。最后,类上应该有两个函数:
addObject()
,其签名取决于ActionPolicy
,即该函数应该在其中定义。execute()
,它会遍历StoragePolicy
存储的所有对象,并对所有对象执行ActionPolicy::evaluate(obj)
。
在(部分伪)代码中(标有 Here
的地方在此设计中不起作用):
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 {
// ...
};
所有这些都是性能关键的,所以我不能只使用向量使用一个条目而不是 StoragePolicySingle
。
你会如何解决这个问题?我缺少任何模式吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么
ActionPolicy
需要了解StoragePolicy
?为什么
ActionPolicy
中添加了对象?如果将
ActionPolicy
作为execute
的参数传递给StoragePolicy
,则对单个项目调用eval
或者收藏,这还不能解决你的问题吗?Why does
ActionPolicy
need to know aboutStoragePolicy
?Why does an
ActionPolicy
have objects added to it?If you pass the
ActionPolicy
to theStoragePolicy
as an argument toexecute
, then calleval
on either the single item or the collection, does this not solve it for you?