具有依赖项的C ++策略设计

编程入门 行业动态 更新时间:2024-10-24 21:33:07
本文介绍了具有依赖项的C ++策略设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是对此问题的跟踪.

基本上,我想要一个存储对象的容器,以后再对它们进行处理.我想将对对象(ActionPolicy)执行的操作和存储(StoragePolicy)都放入策略类.最后,该类上应该有两个函数:

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(),其签名取决于ActionPolicy,即应在此处定义此功能.
  • execute(),它将遍历StoragePolicy存储的所有对象,并对所有对象执行ActionPolicy::evaluate(obj).
  • addObject() with a signature depending on ActionPolicy, i.e. this function should be defined in there.
  • execute(), which goes over all of the objects stored by StoragePolicy and executes ActionPolicy::evaluate(obj) on all of them.

在(部分伪)代码中(标记为Here的位置在该设计中不起作用):

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 { // ... };

所有这些都对性能至关重要,因此我不能只使用带有一个条目的向量来代替StoragePolicySingle.

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?

推荐答案

为什么ActionPolicy需要了解StoragePolicy?

为什么ActionPolicy中添加了对象?

如果将ActionPolicy传递给StoragePolicy作为execute的参数,然后在单个项目或集合上调用eval,这是否为您解决呢?

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?

更多推荐

具有依赖项的C ++策略设计

本文发布于:2023-08-02 11:46:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1277547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:策略

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!