OOP 设计 - 处理整个 Foo 对象序列

OOP design - Process an entire sequence of Foo objects

本文关键字:Foo 对象 设计 处理 OOP      更新时间:2023-10-16

我是面向对象设计的新手,我希望我能得到一些关于设计这个项目的更好方法的建议。

我从一个 FooSequence 类开始,它应该初始化并将一系列 Foo 对象存储在一个向量中。我希望能够从此序列中修改和删除 Foo 对象。也就是说,应用许多算法来处理整个 Foos 序列,并从该序列中删除质量差的 Foos。

不确定我应该如何将 FooSequence 与处理 Foo 对象的类接口。如果有人能详细说明相关的设计模式和陷阱,我将不胜感激。

我想我可以:

a) 扩展 FooSequence 的范围并重命名为 FooProcessor,其中 FooProcessor 的成员函数将处理成员vSequence_

b) 提供访问器和突变器函数,以允许对 Foo 对象进行读写访问。使用另一个类(FooProcessor)从FooSequence修改和删除Foo对象。我不确定应该如何接口。

//A simplified header of the FooSequence class
class FooSequence {
public:
  FooSequence(const std::string &sequence_directory);
  ~FooSequence();
  //To process the sequence, another class must know the capacity of the vector
  //I'm not sure if interfacing to std::vector member functions makes much sense
  std::size_t getSize() const { return vSequence_.size(); }
  //Should I use an accessor that returns a non-const reference??
  //In this case, Why not just make the vector public?
  std::vector<std::shared_ptr<Foo>> getFoo;
  //Return a non-const reference to individual Foo in the sequence??
  //This doesn't help iterate over the sequence unless size of vector is known
  std::shared_ptr<Foo>& operator[] (std::size_t index) { 
  return vSequence_[index];
  }
private:
  const std::string directory_;
  std::vector<std::shared_ptr<Foo>> vSequence_;
  FooSequence(const FooSequence &);
  void operator=(const FooSequence &);
};

我尝试咨询GoF的设计模式,但我认为它对我来说太先进了。任何建议将不胜感激。

编辑:虽然我认为这个问题应该有一个关于面向对象设计的一般性答案,但我认为我应该澄清一下,我希望将ImageSequence类与OpenCV接口。我想知道我可以使用哪些策略或设计来最好地将 ImageSequence 与其他类连接

起来

根据您需要对Foo对象执行哪种处理,我相信将std::vector<std::shared_ptr<Foo>>与STL的标准算法调用结合使用的简单方法就足够了。

您可以使用 STL 做很多事情:

  • 排序
  • 变换
  • 找到
  • 重排
  • 等。。。

所有这些算法都可供您在std::vector上使用,因为标准容器和算法旨在协同工作。

看看cpp首选项的算法列表:

STL算法参考文献

一般设计指南(响应您的编辑)

保持简单。您的设计越简单,维护程序就越容易。如果你的图像序列可以表示为一个简单的向量,那就去做吧。然后,您可以通过迭代图像并处理它们来让其他函数/类对该向量进行操作。

这里有一个简单的作品范围:

for (auto& myImage: myImageVector) {
    // Process my image here
}

for_each是一个结构,允许您将自定义函数应用于容器中的每个元素。

例如,在您的情况下:

myCustomFunction ( Foo& fooObj)
{
    //do something with the foo object
}

现在你可以打电话

for_each(vSequence_.begin(),vSequence_.end(),myCustomFunction)

此语句将为序列中的每个元素执行myCustomFunction

这不是一个设计建议,但是在你的a点的上下文中,只要所有对象需要批处理,FooProcessor就可以使用for_each

我怀疑,你根本不需要那个类。

在现实生活中,你会有一个vector<Mat>(不是vector<shared_ptr<Mat>>,因为Mat已经充当了智能指针)并称之为一天。