Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
Consider the GraphicalObject class defined in Program . The GraphicalObject class implements the GraphicsPrimitives interface. This is indicated by a colon followed by the name of the interface in the declaration of the abstract class.
Program: GraphicalObject class.
The GraphicalObject class has a single field, center, which is a Point that represents the position in a drawing of the center-point of the graphical object. The constructor for the GraphicalObject class takes as its argument a Point and initializes the center field accordingly.
Program shows a possible implementation for the Erase method: In this case we assume that the image is drawn using an imaginary pen. Assuming that we know how to draw a graphical object, we can erase the object by changing the color of the pen so that it matches the background color and then redrawing the object.
Once we can erase an object as well as draw it, then moving it is easy. Just erase the object, change its center point, and then draw it again. This is how the MoveTo method shown in Program is implemented.
We have seen that the GraphicalObject class provides implementations for the Erase and MoveTo methods. However, the GraphicalObject class does not provide an implementation for the Draw method. Instead, the method is declared to be abstract. We do this because until we know what kind of object it is, we cannot possibly know how to draw it!
Consider the Circle class defined in Program . The Circle class extends the GraphicalObject class. Therefore, it inherits the field center and the methods Erase and MoveTo. The Circle class adds an additional field, radius, and it overrides the Draw method. The body of the Draw method is not shown in Program . However, we shall assume that it draws a circle with the given radius and center point.
Using the Circle class defined in Program we can write code like this:
Circle c = new Circle(new Point(0, 0), 5); c.Draw (); c.MoveTo(new Point(10, 10)); c.Drase ();This code sequence declares a circle object with its center initially at position (0,0) and radius 5. The circle is then drawn, moved to (10,10), and then erased.
Program defines the Rectangle class and Program defines the Square class. The Rectangle class also extends the GraphicalObject class. Therefore, it inherits the field center and the methods Erase and MoveTo. The Rectangle class adds two additional fields, height and width, and it overrides the Draw method. The body of the Draw method is not shown in Program . However, we shall assume that it draws a rectangle with the given dimensions and center point.
The Square class extends the Rectangle class. No new fields or methods are declared--those inherited from GraphicalObject or from Rectangle are sufficient. The constructor simply arranges to make sure that the height and width of a square are equal!