今回はその6、7、8のDecoratorパターンをVBに直します。(コードが長くなるので、3回に分けます。)
では早速、まずはその6のコードから。
Public MustInherit Class AbstractFood
Protected _description As String = "食品の説明"
Public Overridable ReadOnly Property Description() As String
Get
Return Me._description
End Get
End Property
Public MustOverride Function GetPrice() As Decimal
End Class
Public MustInherit Class AbstractDecorator
Inherits AbstractFood
Public MustOverride Overrides ReadOnly Property Description() As String
End Class
Public Class Gyudon
Inherits AbstractFood
Public Sub New()
Me._description = "牛丼"
End Sub
Public Overrides Function GetPrice() As Decimal
Return 380D
End Function
End Class
Public Class Kimuchi
Inherits AbstractDecorator
Private _food As AbstractFood
Public Sub New(ByVal food As AbstractFood)
Me._food = food
End Sub
Public Overrides ReadOnly Property Description() As String
Get
Return Me._food.Description + ",キムチ"
End Get
End Property
Public Overrides Function GetPrice() As Decimal
Return Me._food.GetPrice() + 100D
End Function
End Class
Public Class Tsuyudaku
Inherits AbstractDecorator
Private _food As AbstractFood
Public Sub New(ByVal food As AbstractFood)
Me._food = food
End Sub
Public Overrides ReadOnly Property Description() As String
Get
If TypeOf Me._food Is Tsuyudaku Then
Return Me._food.Description + "だく"
Else
Return Me._food.Description + ",つゆだく"
End If
End Get
End Property
Public Overrides Function GetPrice() As Decimal
Return Me._food.GetPrice() + 0D
End Function
End Class
Public Shared Sub Main(ByVal args As String())
Dim order As AbstractFood = New Gyudon()
Console.WriteLine("説明:{0}", order.Description)
Console.WriteLine("価格:{0:N} 円", order.GetPrice())
order = New Kimuchi(order)
Console.WriteLine("説明:{0}", order.Description)
Console.WriteLine("価格:{0:N} 円", order.GetPrice())
order = New Tsuyudaku(order)
Console.WriteLine("説明:{0}", order.Description)
Console.WriteLine("価格:{0:N} 円", order.GetPrice())
order = New Tsuyudaku(order)
Console.WriteLine("説明:{0}", order.Description)
Console.WriteLine("価格:{0:N} 円", order.GetPrice())
Console.ReadLine()
End Sub
実行結果
説明:牛丼
価格:380.00 円
説明:牛丼,キムチ
価格:480.00 円
説明:牛丼,キムチ,つゆだく
価格:480.00 円
説明:牛丼,キムチ,つゆだくだく
価格:480.00 円
いかがでしょうか?
今回のポイントはC#とVBのキーワードの違いですかね。(以下C# <=> VB)
- abstract class <=> MustInherit Class
- abstract [メソッド/プロパティ] <=> MustOverride [メソッド/プロパティ]
- virtual <=> Overridable
- override <=> Overrides
あと、読み取り専用プロパティの書き方もちがいますね。
- C#:getアクセサのみコードを書く。
- VB:プロパティ宣言で「ReadOnly」キーワードが必要。そのうえで、Getアクセサのみコードを書く。
この辺りをしっかりと理解しておけば、C#<=>VBの読み替えもそれほど苦にはならないと思います。