C++ Policy design with dependencies

拜拜、爱过 提交于 2019-12-11 05:14:30

问题


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 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!