VB
'
'(C) OOMusou 2007 http://oomusou.cnblogs.com
'Filename : DP_AdpaterPattern_Strategy_Class.vb
'Compiler : VB 9
'Description : Demo how to use Strategy Pattern with Adapter Pattern (Class)
'Release : 07/12/2007 1.0
'
Imports System
Interface IDrawStrategyInterface IDrawStrategy
Sub draw()Sub draw()
End Interface
Class GrapherClass Grapher
Protected _drawStrategy As IDrawStrategy
Public Sub New()Sub New(Optional ByRef drawStrategy As IDrawStrategy = Nothing)
_drawStrategy = drawStrategy
End Sub
Public Sub drawShape()Sub drawShape()
If _drawStrategy IsNot Nothing Then
_drawStrategy.draw()
End If
End Sub
Public Sub setShape()Sub setShape(ByRef drawStrategy As IDrawStrategy)
_drawStrategy = drawStrategy
End Sub
End Class
Interface IPaintInterface IPaint
Sub paint()Sub paint()
End Interface
Class TriangleClass Triangle
Implements IPaint
Public Sub paint()Sub paint() Implements IPaint.paint
Console.WriteLine("Draw Triangle")
End Sub
End Class
Class CircleClass Circle
Implements IPaint
Public Sub paint()Sub paint() Implements IPaint.paint
Console.WriteLine("Draw Circle")
End Sub
End Class
Class SquareClass Square
Implements IPaint
Public Sub paint()Sub paint() Implements IPaint.paint
Console.WriteLine("Draw Square")
End Sub
End Class
Class TriangleDrawAdapterClass TriangleDrawAdapter
Inherits Triangle
Implements IDrawStrategy
Public Sub draw()Sub draw() Implements IDrawStrategy.draw
Me.paint()
End Sub
End Class
Class CircleDrawAdapterClass CircleDrawAdapter
Inherits Circle
Implements IDrawStrategy
Public Sub draw()Sub draw() Implements IDrawStrategy.draw
Me.paint()
End Sub
End Class
Class SquareDrawAdapterClass SquareDrawAdapter
Inherits Square
Implements IDrawStrategy
Public Sub draw()Sub draw() Implements IDrawStrategy.draw
Me.paint()
End Sub
End Class
Class ClientClass ClIEnt
Shared Sub Main()Sub Main()
Dim grapher As Grapher = New Grapher(New TriangleDrawAdapter())
grapher.drawShape()
grapher.setShape(New CircleDrawAdapter())
grapher.drawShape()
grapher.setShape(New SquareDrawAdapter())
grapher.drawShape()
End Sub
End Class
執行結果
Draw Triangle
Draw Circle
Draw Square
Class Adapter的缺點在此范例很明顯,因為使用繼承技術,所以每個Class需要有相對應的Adapter,使用泛型可以稍微解決此問題,不過僅能使用ISO C++和C++/CLI的template來解決,C#、C++/CLI、VB的Generics都無福消受,請參閱 (原創) 我的Design Pattern之旅[7]:使用泛型改進Adapter Pattern (OO) (Design Pattern) (C/C++) (template) (C++/CLI)。