class AbstractShape;
class RectangularShape : public AbstractShape
{
void setWidth(double v);
void setLength(double v);
};
class CircleShape : public AbstractShape
{
void setRadius(double v);
};
class PolygonalShape : public AbstractShape
{
void addPoint(Point p);
};
class Element
{
protected:
AbstractShape* _shape; //RectangularShape, PolygonalShape or CircleShape
};
Elementのシェイプを変更するには、Elementのシェイプを作成する必要があります(シェイプがRectangularの場合、長さと幅を変更できる必要があります。多角形などにポイントを追加することができるなど)。抽象的な属性を変更するインタフェース
たとえば、setLengthは_shapeがRectangularShapeの場合にのみ意味があるため、setLengthメソッドを宣言することはできません。解決策は、RectangularElement、PolygonalElement、CircularElementのElementをサブクラス化することですが、この解決法を避けたいと思います。 これを行う別の方法がありますか?
class Shape
{
// ....
virtual void setWidth(double v) { /* not implemented, throw error ? */ }
virtual void setLength(double v){ /* not implemented, throw error ? */}
virtual void setRadius(double v){ /* not implemented, throw error ? */}
virtual void addPoint(Point p) { /* not implemented, throw error ? */}
//....
};
class RectangularShape : public Shape
{
void setWidth(double v) override ;
void setLength(double v) override;
};
class CircleShape : public Shape
{
void setRadius(double v) override ;
};
class PolygonalShape : public Shape
{
void addPoint(Point p) override;
};
class Element
{
protected:
Shape* _shape; //Any shape
};
をメッセージを印刷したりアサートします_shape
に無意味関数を呼び出す:
ビジターパターン? – StoryTeller
矩形もポリゴンでなければなりません。多角形をモーフする間接レイヤーを追加することを検討してください。 – Curious
@ user1482030太いインターフェイスが必要なのですか? – Curious