程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 我的Design Pattern之旅[6]:Adapter Pattern(OO)(10)

我的Design Pattern之旅[6]:Adapter Pattern(OO)(10)

編輯:關於C語言

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)。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved