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
Object Adapter的優點在此范例可以明顯看出,只需一個DrawAdapter就可轉換所有class,未來若有新的class,也不需再修改DrawAdapter,符合OCP原則,且又可動態載入不同的Adaptee。
Conclusion
Design Pattern的修為重在了解class間該如何布局以解決問題,但坊間講Design Pattern的書大都用C++或Java,C#很少,VB更少,本文同時用了ISO C++、C#、C++/CLI、VB來實現Adapter Pattern,各位讀者可依自己的需要,選擇自己喜歡的語言來了解Adapter Pattern。