标题说明了一切。
我需要一个多态性是唯一解决方案的场景。我已经看到许多线程具有多态性的好处,但我认为,缺少仅具有多态性的解决方案。
提出同一问题的另一种方式是:
"多态性的起源是什么?"
答案 0 :(得分:0)
你的问题在某种程度上可以解释。
让我先试着回答你的问题:
多态性的默认示例可能是矢量图形工具,例如, Corel Draw,Inkscape。 假设您希望用户能够在画布上绘制几种不同的地理形状(正方形,三角形,圆形)。
我现在建议多态性的CONCEPT是该问题的唯一解决方案,同时当然您将能够很好地编写任何编程语言的解决方案,包括那些不提供完整多态性机制的解决方案(如例如C)。
显式多态性将以几种形式变得明显,如果'条件。
所以: 多态的概念总是唯一的解决方案,如果:
关于“来源”问题的补充问题。多态性。 多态性的概念是突出的,就像Primes一样,至少我有这种感觉。 编程语言中多态性的隐式支持始于90年代早期的C ++,早期的WYSWG程序,如Corel Draw和Word以及 THE book (这当然是个人观察)
下面是一个例子。
// example WITH implicit polymorphism
abstract class PolyGeometricEntity
{
public int center_x__mm; // commen superset
public int center_y__mm; // commen superset
public void move(int d_x__mm, int d_y_mm) // commen superset
{
center_x__mm += d_x__mm;
center_y__mm += d_y_mm:
}
public abstract int area(); // commen superset on abstract level, but specialized at implementation level
public abstract void draw(); // commen superset on abstract level, but specialized at implementation level
}
class CircleEntity : PolyGeometricEntity
{
public override int area()
{
// circle specific
return 1;
}
public override void draw()
{
// draw a circle
}
}
class TriangleEntity : PolyGeometricEntity
{
public override int area()
{
// triangle specific
return 1;
}
public override void draw()
{
// draw a triangle
}
}
class PolyCanvas
{
List<PolyGeometricEntity> entities = new List<PolyGeometricEntity>();
void CreateEntity(string toCreateClass)
{
// assume that code is called by the ui
// you do not know what the user decides at runtime
// Polymorphism 'starting' now:
PolyGeometricEntity toCreate = null;
if (toCreateClass == "c") { toCreate = new CircleEntity(); }
else if (toCreateClass == "t") { toCreate = new TriangleEntity(); }
entities.Add(toCreate);
}
void ReDraw()
{
foreach (PolyGeometricEntity toDraw in entities)
{
toDraw.draw(); // polymorphism in action!
}
}
}
// example WITHOUT implicit polymorphism
abstract class NonPolyGeometricEntity
{
public int center_x__mm; // commen superset
public int center_y__mm; // commen superset
public string entityClass;
public void move(int d_x__mm, int d_y_mm) // commen superset
{
}
// explicid Polymorphism, but concept of Polymorphism still present
public int area()
{
if (entityClass == "c")
{
// return area of cirlce
}
else if (entityClass == "t")
{
// return area of triangle
}
return 0;
}
public void draw()
{
if (entityClass == "c")
{
// draw area of cirlce
}
else if (entityClass == "t")
{
// draw area of triangle
}
}
}
class NonPolyCanvas
{
List<NonPolyGeometricEntity> entities = new List<NonPolyGeometricEntity>();
void CreateEntity(string toCreateClass)
{
// assume that code is called by the ui
// you do not know what the user decides at runtime
NonPolyGeometricEntity toCreate = null;
toCreate.entityClass = toCreateClass; //explit polymorphism
entities.Add(toCreate);
}
void ReDraw()
{
foreach (NonPolyGeometricEntity toDraw in entities)
{
toDraw.draw();
}
}
}