C ++类/层次结构设计

时间:2011-11-08 13:47:46

标签: c++

我大致说出以下等级

class Base {
public:
    virtual int value() const = 0;
};

class Derived1 : public Base {
public:
    int value() const {
        return 1;
    }
};

class Derived2 : public Base {
public:
    int value() const {
        return -1;
    }
};

class Derived3 : public Base {
public:
    Derived3(const Base & underlying);
    int value() const {
        return underlying_.value() + 10;
    }
private:
    const Base & underlying_;
};

Derived3::Derived3(const Base & underlying)
:underlying_(underlying) {}

Base对象还有一个单例持有者。工作流程的一个分支是这样的:
1)从持有人中获取Derived1对象
2)使用Derived1对象实例化Derived3对象并使用它。

我处于多线程环境中,我担心在第二个对象的生命周期中,unders_ reference_的问题会变得无效。我不是多线程的专家,但我相信这可能发生。

我希望Derived2对象拥有底层对象的副本但是因为Base是抽象的我不能这样做。有人可以对此设计发表评论并提出不同的方法。

另外,上述设计背后有两个驱动思路。 Derived3应该是Base类型对象的移位。一种愿望是轮班的转变。另一个愿望是能够将Derived3对象存储在单例中以供以后使用。

2 个答案:

答案 0 :(得分:1)

当您只有一个指针或对抽象类的引用时,克隆是制作副本的常用方法。

struct A {
  virtual A* clone() const = 0;
  virtual ~A() { }
};

struct B : A {
  virtual A* clone() const { return new B(*this); }
};

struct C {
  A* ap;

  C(A* ap_arg) : ap(ap_arg->clone()) { }
  ~C() { delete ap; }
};

答案 1 :(得分:1)

您可以尝试“克隆”您的课程。我的意思是,每个派生类都可以克隆自己并在其他派生中使用此克隆。

class Base {
    public:
        virtual Base *clone() const = 0;
};

class Derived2 : public Base {
    public:
        int value() const {
           return -1;
        }
        Derived2(const Derived2 &)
        {
            ....
        }
        Base *clone() const
        {
            return new Derived2(*this);
        }
};

使用此解决方案,您可以随时保留新的Derived。别忘了删除它。您的工厂返回一个可以克隆以获取新对象的Base对象。

相关问题