using System;
namespace Polymorphism
{
class Shape
{
public virtual void draw()
{
Console.WriteLine("Draw shape....");
}
}
class Circle: Shape
{
public override void draw()
{
Console.WriteLine("Draw circle....");
}
}
class Triangle : Shape
{
public override void draw()
{
Console.WriteLine("Draw triangle....");
}
}
class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("Draw rectangle...");
}
}
class Create
{
public Shape CreateShape(string str)
{
Shape s;
switch (str)
{
case "c":
s = new Circle();
break;
case "r":
s = new Rectangle();
break;
case "t":
s = new Triangle();
break;
default:
s = new Shape();
break;
}
return s;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please type a Shape class you want to create: ");
string strShape = Console.ReadLine();
Console.WriteLine("string is: {0}", strShape);
Create c = new Create();
Shape s = c.CreateShape(strShape);
s.draw();
Console.ReadLine();
}
}
}
In the above example, if we want to add a new class to draw Oval shape, we will have a class like:
class Oval: Shape
{
public override void draw()
{
Console.WriteLine("Draw oval....");
}
}
We want to be able to ‘plug-in’ this class into our application without having to make any code changes in the original code and call the draw() of Oval class during run time. By using Polymorphism, the only place we need to make the change is our Create method and we leave our client application code untouched.
Understanding polymorphism is key to designing scalable, plug-and-play architecture application.
No comments:
Post a Comment