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

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

     編輯:關於C語言

C# 版物件適配器實作,架構同前:Grapher 依賴 IDrawStrategy,既有類別實作 IPaint,DrawAdapter 組合 IPaint 並轉呼叫 paint()。

完整程式碼

using System;

interface IDrawStrategy { void draw(); }

class Grapher {
    protected IDrawStrategy _drawStrategy = null;
    public Grapher() {}
    public Grapher(IDrawStrategy ds) { _drawStrategy = ds; }
    public void drawShape() { if (_drawStrategy != null) _drawStrategy.draw(); }
    public void setShape(IDrawStrategy ds) { _drawStrategy = ds; }
}

interface IPaint { void paint(); }

class Triangle : IPaint { public void paint() { Console.WriteLine("Draw Triangle"); } }
class Circle : IPaint { public void paint() { Console.WriteLine("Draw Circle"); } }
class Square : IPaint { public void paint() { Console.WriteLine("Draw Square"); } }

class DrawAdapter : IDrawStrategy {
    protected IPaint _adaptee = null;
    public DrawAdapter() {}
    public DrawAdapter(IPaint adaptee) { _adaptee = adaptee; }
    public void draw() { _adaptee.paint(); }
}

class Client {
    static void Main() {
        Grapher 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();
    }
}

執行結果

Draw Triangle
Draw Circle
Draw Square

物件適配器採用組合而非繼承,單一適配器類別即可處理所有 IPaint 實作,符合「多用組合、少用繼承」原則,且支援執行期動態切換被適配物件。

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