首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

我的設計模式之旅[6]:Adapter Pattern 與 Strategy Pattern 結合 VB 實作 (物件適配器)

     編輯:關於C語言

本文展示 VB.NET 版本,結合 Strategy Pattern 與 Adapter Pattern(物件適配器),讓 Grapher 能使用既有 IPaint 介面的繪圖類別。

核心架構

  • IDrawStrategy:Grapher 期望的策略介面,定義 draw()
  • IPaint:既有框架提供的介面,定義 paint()
  • DrawAdapter:實作 IDrawStrategy,內部組合 IPaint 物件,draw() 呼叫 paint()

VB.NET 完整程式碼

Imports System

Interface IDrawStrategy
    Sub draw()
End Interface

Class Grapher
    Protected _drawStrategy As IDrawStrategy
    Public Sub New(Optional ByRef drawStrategy As IDrawStrategy = Nothing)
        _drawStrategy = drawStrategy
    End Sub
    Public Sub drawShape()
        If _drawStrategy IsNot Nothing Then _drawStrategy.draw()
    End Sub
    Public Sub setShape(ByRef drawStrategy As IDrawStrategy)
        _drawStrategy = drawStrategy
    End Sub
End Class

Interface IPaint
    Sub paint()
End Interface

Class Triangle : Implements IPaint
    Public Sub paint() Implements IPaint.paint
        Console.WriteLine("Draw Triangle")
    End Sub
End Class
Class Circle : Implements IPaint
    Public Sub paint() Implements IPaint.paint
        Console.WriteLine("Draw Circle")
    End Sub
End Class
Class Square : Implements IPaint
    Public Sub paint() Implements IPaint.paint
        Console.WriteLine("Draw Square")
    End Sub
End Class

Class DrawAdapter : Implements IDrawStrategy
    Protected _adaptee As IPaint
    Public Sub New(Optional ByRef adaptee As IPaint = Nothing)
        _adaptee = adaptee
    End Sub
    Public Sub draw() Implements IDrawStrategy.draw
        _adaptee.paint()
    End Sub
End Class

Class Client
    Shared Sub Main()
        Dim grapher As Grapher = New Grapher(New DrawAdapter(New Triangle()))
        grapher.drawShape()
        grapher.setShape(New DrawAdapter(New Circle()))
        grapher.drawShape()
        grapher.setShape(New DrawAdapter(New Square()))
        grapher.drawShape()
    End Sub
End Class

執行結果

Draw Triangle
Draw Circle
Draw Square

物件適配器優勢

單一 DrawAdapter 即可轉換所有實作 IPaint 的類別,新增形狀無需修改適配器,符合開放封閉原則 (OCP),且支援執行期動態切換被適配物件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved