dimanche 18 octobre 2020

Returning Decorator object in decorator design pattern C++

I am doing an exercise for my university, where I have to create a Vector3D class using the Decorator design pattern. enter image description here

[edit 1: One thing to note here, my professor told us to merge Decorator and ConcreteDecorator into one class - Vector3D, if I understood correctly]

And this is what I came with.

class Vector3D : public IVector
{
    std::shared_ptr<IVector> vector2D;
    double z;
public:
    Vector3D(IVector* vector2D, double z);
    double abs() const override;
    std::vector<double> getComponents() const override;
    std::vector<double> getAngles() const override;
    double cdot(const IVector& vector) const override;
};

Then I had to implement a function that returns a cross product of two vectors. I know how to compute the coordinates, however, I don't know how to construct the object, since my constructor accepts any object of a class that implements IVector and IVector itself does not have a constructor.

Vector3D Vector3D::crossProduct(const IVector &vector) const
{
    const auto v = vector2D->getComponents();
    const auto coords = vector.getComponents();
    if(coords.size() != 3)
        throw std::runtime_error("Given vector has wrong number of components");

    return ???
}

Should I just create this object using Vector2D's constructor, or does it kinda break the design pattern? Is there something that I have mixed up?

[edit 2: I am wondering if it is possible to get the type of the object pointed by std::shared_ptr<IVector> vector2D field and use its constructor somehow?]

Aucun commentaire:

Enregistrer un commentaire