具有依赖项的C ++策略设计 [英] C++ Policy design with dependencies

查看:101
本文介绍了具有依赖项的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 ++策略设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆