This post discusses how to change the software architecture of the Test Diagram project to support the creation of multiple components of different types with different graphical representations. For example, we would like to create rectangles, circles, diamonds, triangles, etc. The form Paint event handler loops throught the list of components and calls the component Draw() method. How can we change the system so that the foreach loop will call the correct Draw() method for any shape or component type?
Time to use Inheritance and Polymorphism. Poly-What-ism? Polymorphism is a fancy OOP word for classes that call methods based on the class type inherited from a base class. There is some magic involved in this process but it works very well. We need to do the following:
- Define a base class for all components
- Create Virtual methods for all methods that are called in iterators - Draw()
- Create a class for each component which inherits from the base class
- Create a Draw() method that "overrides" the base class virtual method
- Create menu buttons for each component type
- Create menu button handlers to create the associated component and add it to the component list
public virtual void
Draw(Graphics gr)
{
// Draw a simple rectangle with black border and no fill color
gr.DrawRectangle(pen, 100,
100, 100, 100);
}
using System;
using System.Collections.Generic;
using System.Drawing;
namespace TestDiagram
{
class Rectangle : Comp
{
public Rectangle()
{
}
public override void
Draw(Graphics gr)
{
// Draw a simple rectangle with black border and no fill color
gr.DrawRectangle(pen, 250, 100, 100, 100);
}
}
}
- Text: Rectangle
- Name: btnRectangle
No comments:
Post a Comment