设计思路
- 抽象基类 Shape:定义所有图形共有的属性和方法,作为其他具体图形类的基类。这里将
Draw
方法定义为抽象方法,具体图形类必须实现此方法,以此实现多态。
- 具体图形类:如
Circle
和 Rectangle
,继承自 Shape
类,实现抽象方法,并拥有各自特有的属性。
- 使用多态:在绘制图形时,通过创建不同具体图形类的实例,并调用它们的
Draw
方法,而不需要关心具体是哪种图形,由运行时根据对象的实际类型决定调用哪个类的 Draw
方法。
代码框架
' 抽象基类 Shape
Public MustInherit Class Shape
' 通用属性
Protected color As String
Public Property Color() As String
Get
Return color
End Get
Set(ByVal value As String)
color = value
End Set
End Property
' 抽象方法,具体图形类必须实现
Public MustOverride Sub Draw()
End Class
' Circle 类,继承自 Shape
Public Class Circle
Inherits Shape
' 特有属性
Private radius As Double
Public Property Radius() As Double
Get
Return radius
End Get
Set(ByVal value As Double)
radius = value
End Set
End Property
' 实现 Draw 方法
Public Overrides Sub Draw()
' 实际绘制圆形的代码,这里用简单输出模拟
Console.WriteLine("绘制一个半径为 {0},颜色为 {1} 的圆形", radius, color)
End Sub
End Class
' Rectangle 类,继承自 Shape
Public Class Rectangle
Inherits Shape
' 特有属性
Private width As Double
Private height As Double
Public Property Width() As Double
Get
Return width
End Get
Set(ByVal value As Double)
width = value
End Set
End Property
Public Property Height() As Double
Get
Return height
End Get
Set(ByVal value As Double)
height = value
End Set
End Property
' 实现 Draw 方法
Public Overrides Sub Draw()
' 实际绘制矩形的代码,这里用简单输出模拟
Console.WriteLine("绘制一个宽为 {0},高为 {1},颜色为 {2} 的矩形", width, height, color)
End Sub
End Class
多态性的实现
Module Program
Sub Main()
' 创建不同图形的实例
Dim circle As New Circle()
circle.Color = "红色"
circle.Radius = 5
Dim rectangle As New Rectangle()
rectangle.Color = "蓝色"
rectangle.Width = 10
rectangle.Height = 5
' 定义一个 Shape 类型的数组
Dim shapes() As Shape = {circle, rectangle}
' 遍历数组,调用 Draw 方法,实现多态
For Each shape As Shape In shapes
shape.Draw()
Next
End Sub
End Module