【发布时间】:2018-01-31 02:04:29
【问题描述】:
我正在尝试创建一个仅实例化一次的类 ShapeManager,并且有一个基类 Shape(及其所有子类)可以访问它。这将导致结构如下所示:
ShapeManagerShape
└Square
└Triangle
└Circle
#include "Shape.h" // so that i can use Shape in the vector
// This is instantiated once in main
class ShapeManager {
public:
typedef std::vector<std::unique_ptr<Shape>> VecShape;
typedef std::default_random_engine DRE;
private:
VecShape& m_shapes;
b2World& m_world;
DRE& m_gen;
public:
ShapeManager(VecShape& vectorShapes, b2World& world, DRE& gen)
: m_shapes(vectorShapes), m_world(world), m_gen(gen) {}
VecShape& getShapeList() { return m_shapes; }
b2World& getWorld() { return m_world; }
DRE& getDRE() { return m_gen; }
};
#include "ShapeManager.h" // so that i can access it's member functions
class Shape {
protected:
std::string m_name;
public:
Shape() : m_name("Shape") {}
std::string getName() { return m_name; }
};
我大大简化了我的代码以使其与我的问题相关。如果不清楚我在问什么,我会尝试进一步解释!
基本上我只想有一个类来管理我的形状对象并保存Shape's儿童将使用的数据,例如m_gen和m_world。
编辑 1:我创建 ShapeManager 的主要动机是存储对 m_shapes、m_world 和 m_gen 的引用,但我不希望每个形状对象都具有这 3 个引用变量。这意味着创建 Circle 必须在 ctor 中包含这 3 个参数,以及与圆相关的参数。
编辑 2:单例和/或依赖注入是两种设计模式,在实施时可以解决我的问题。 Here is some info on it.谢谢大家!
【问题讨论】:
-
您可以存储
ShapeManager(或类似的任何东西)的全局实例并使用它。 -
警告:ShapeManager.h 包含 Shape.h,Shape.h 包含 ShapeManager.h。这是一个循环依赖。阅读Resolve build errors due to circular dependency amongst classes 可能会阻止未来的问题。
-
为什么形状需要与形状管理器交互?我希望反过来。您可能将管理和服务混为一谈。
-
我尝试在 main() 上方声明一个全局 ShapeManager,但 Shape 的子级仍然无法访问它。
-
你在问如何制作一个 singleton 对象。这是一个众所周知的(虽然并不总是喜欢)模式,现在您知道要搜索什么词,使用它不会有任何问题。
标签: c++ inheritance