双重调度和工厂模式

时间:2015-03-07 07:35:34

标签: c++ oop hierarchy double-dispatch

我目前有以下代码(不工作):

#include <iostream>
#include <vector>

class Circle;
class Rectangle;

class Shape {
private:
    Shape() {};
public:
    virtual ~Shape() {};
    friend class Circle;
    friend class Rectangle;
};

class Creator {
public:
    virtual ~Creator() {};
    virtual Shape* create() = 0;
    virtual bool equals(Shape& s) { return false; };
};

class Circle : public Shape {
private:
    Circle() : Shape() {};
public:
    class CircleCreator : public Creator {
    public:
        virtual Shape* create() { return new Circle(); };
        virtual bool equals(Shape& other_shape) { return false; };
    };
};

class Rectangle : public Shape {
private:
    Rectangle() : Shape() {};
public:
    class RectangleCreator : public Creator {
    public:
        virtual Shape* create() { return new Rectangle(); };
        virtual bool equals(Shape& other_shape) { return false; };
    };
};

int main() {
    /* First step, build the list */
    std::vector<Shape*> shapeList;
    std::vector<Shape*>::iterator it;
    Rectangle::RectangleCreator rc;
    Circle::CircleCreator cc;
    Shape* s = cc.create();
    Shape* s1 = rc.create();
    shapeList.push_back(s);
    shapeList.push_back(s1);

    /* Second step: check if we've got a shape starting from a creator */
    for (it = shapeList.begin(); it != shapeList.end(); ++it) {
        if (rc.equals(**it)) {
            std::cout << "same shape" << std::endl;
        }
    }
    return 0;
}

我的目标是使用工厂模式,如果在列表中我已经拥有该对象,则避免创建新对象。我试图使用双重调度模式,但在这种情况下它并不容易应用。我该怎么办?

编辑:由于代码用于&#34;关键&#34;路径,我想避免使用像dynamic_cast这样的RTTI。

2 个答案:

答案 0 :(得分:1)

也许这样的事情可以使用成员变量来实现

#include <iostream>
#include <vector>

enum
{
CIRCLE,
RECTANGLE
};

class Circle;
class Rectangle;

class Shape {
private:
    Shape() {};
public:
    unsigned shapeType;
    virtual ~Shape() {};
    friend class Circle;
    friend class Rectangle;
};

class Creator {
public:
unsigned shapeType;
    virtual ~Creator() {};
    virtual Shape* create() = 0;
    bool equals(Shape& s) { return (this->shapeType == s.shapeType); };
};

class Circle : public Shape {
private:
    Circle() : Shape() {shapeType=CIRCLE;};
public:
    class CircleCreator : public Creator {
    public:
        CircleCreator() {shapeType=CIRCLE;};
        virtual Shape* create() { return new Circle(); };
    };
};

class Rectangle : public Shape {
private:
    Rectangle() : Shape() {shapeType=RECTANGLE;};
public:
    class RectangleCreator : public Creator {
    public:
        RectangleCreator() {shapeType=RECTANGLE;};
        virtual Shape* create() { return new Rectangle(); };
    };
};

int main() {
    /* First step, build the list */
    std::vector<Shape*> shapeList;
    std::vector<Shape*>::iterator it;
    Rectangle::RectangleCreator rc;
    Circle::CircleCreator cc;
    Shape* s = cc.create();
    Shape* s1 = rc.create();
    shapeList.push_back(s);
    shapeList.push_back(s1);

    /* Second step: check if we've got a shape starting from a creator */
    for (it = shapeList.begin(); it != shapeList.end(); ++it) {
        if (rc.equals(**it)) {
            std::cout << "same shape" << std::endl;
        }
    }
    return 0;
}

或者 - 使用虚函数返回类型

#include <iostream>
#include <vector>

enum
{
    CIRCLE,
RECTANGLE,
UNKNOWN
};
class Circle;
class Rectangle;

class Shape {
private:
    Shape() {};
public:
    virtual ~Shape() {};
    friend class Circle;
    friend class Rectangle;
    virtual unsigned iAmA(){return UNKNOWN;};
};

class Creator {
public:
    virtual ~Creator() {};
    virtual Shape* create() = 0;
    virtual bool equals(Shape& s) { return false; };
};

class Circle : public Shape {
private:
    Circle() : Shape() {};
    virtual unsigned iAmA(){return CIRCLE;};
public:
    class CircleCreator : public Creator {
    public:
        CircleCreator() {};
        virtual Shape* create() { return new Circle(); };
        virtual bool equals(Shape& other_shape) { return (CIRCLE == other_shape.iAmA()); };
    };
};

class Rectangle : public Shape {
private:
    Rectangle() : Shape() {};
    virtual unsigned iAmA(){return RECTANGLE;};
public:
    class RectangleCreator : public Creator {
    public:
        RectangleCreator() {};
        virtual Shape* create() { return new Rectangle(); };
        virtual bool equals(Shape& other_shape) { return (RECTANGLE == other_shape.iAmA()); };
    };
};

int main() {
    /* First step, build the list */
    std::vector<Shape*> shapeList;
    std::vector<Shape*>::iterator it;
    Rectangle::RectangleCreator rc;
    Circle::CircleCreator cc;
    Shape* s = cc.create();
    Shape* s1 = rc.create();
    shapeList.push_back(s);
    shapeList.push_back(s1);

    /* Second step: check if we've got a shape starting from a creator */
    for (it = shapeList.begin(); it != shapeList.end(); ++it) {
        if (rc.equals(**it)) {
            std::cout << "same shape" << std::endl;
        }
    }
    return 0;
}

答案 1 :(得分:0)

我不确定你要做什么,但我想这可能会为你指明方向

enum class Shapes
{
    Rectangle,
    Circle,
    ...
};

class Shape
{
private:
    Shapes m_shape;

protected:
    Shape(Shapes shape)
    {
        m_shape = shape;
    }

public:
    Shapes GetShape() { return m_shape; } // this is used to check whether two shapes are equal

    virtual ~Shape() = default;
};

现在,对于工厂模式,您可以:

class ShapeFactory
{
public:
    static Shape* CreateShape(Shapes shape)
    {
        switch (shape)
        {
            case Shapes::Circle:
                return new Circle();
            // etc.
        }
    }
};

这感觉非常多余,对我来说不是很聪明。此外,这可以将大量代码放在一个地方。

对于发送,您可以这样做(我认为,我并不是这个概念的粉丝,因为使用简单的模板可以减少冗长)

class ShapeCreator
{
public:
    virtual Shape* Create() = 0;
    virtual ~ShapeCreator() = default;
};

class Circle : public Shape
{
public:
    class Creator : ShapeCreator
    {
    public:
        Shape* Create() { return new Circle(); }
    };

    Circle() : Shape(Shapes::Circle)
    {}
};

bool SomethingWithCircle()
{
    Circle::Creator circleCreator;
    Shape* first = circleCreator.Create();
    Shape* second = circleCreator.Create();

    // notice memleak here
    return first->GetShape() == second->GetShape();
}

如果使用C ++ 11,你可以更进一步,避免整个想法/无论如何感觉非常像java /使用适当的模板手淫技术。 (仍然可以应用于pre-C ++ 11,您只是赢得了无法指定参数。)

template<class T>
class ShapeCreator
{
public:
    template<class... TParams>
    static T* Create(TParams&&... parameters) { return new T(std::forward<TParams>(parameters)...); }
};

class Rectangle : public Shape
{
private:
    int m_width;
    int m_height;

public:
    Rectangle(int width, int height) : Shape(Shapes::Rectangle)
    {
        m_width = width;
        m_height = height;
    }
};

bool DoSomethingWithRectangles()
{
    Rectangle* first  = ShapeCreator<Rectangle>::Create(10, 15);
    Shape* second     = ShapeCreator<Rectangle>::Create(20, 25);

    // notice memleak here
    return first->GetShape() == second->GetShape();
}

TL; DR
您并不真正需要RTTI,但您需要在基本类型的某处存储类型信息。我正在使用enum Shapes
Factory和Dispatch都可能看起来不错,但在使用它们时仍需要动态施法 您可以使用模板替换这两种模式,但只要您获得基础对象的向量,您在某些时候仍然需要dynamic_cast
我没有做任何测量,但我对使用虚拟功能和动态演员的性能比较非常感兴趣,因为我认为它们非常相似...

结束说明:
请注意,我个人认为在定义基本界面的类上使用equalsoperator==等方法并不是很明智,因为有两种可能的结果:

  1. equals是虚拟的 - &gt;
  2. equals不是虚拟的 - &gt;不能在继承类型中用于实际进行更高级/相关的比较,打破Open to extension, closed for modification
  3. 的想法

    显然,如果您没有定义equals,那么您每次都必须编写比较代码。或者可能使用一些模板Comparison类,通过特征可能的特化,再次产生最佳性能,没有代码重复性。

    一般来说,你可以指出你自己问的问题&#34;为什么没有像java或c#中的基础对象和反射?这将允许我使用所有这些漂亮和聪明的模式。&#34;答案是模板。为什么运行时,你可以编译时间?