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

我的設計模式之旅[6]:Adapter Pattern 類別適配器 C# 實作

     編輯:關於C語言

C# 版類別適配器:TriangleDrawAdapter 繼承 Triangle 並實作 IDrawStrategy。C# 單一繼承限制,僅能繼承一個類別,故適配器必須繼承具體類別而非介面。

程式碼片段

class TriangleDrawAdapter : Triangle, IDrawStrategy {
    public void draw() { paint(); }
}

完整程式碼

using System;

interface IDrawStrategy { void draw(); }
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 TriangleDrawAdapter : Triangle, IDrawStrategy { public void draw() { paint(); } }
class CircleDrawAdapter : Circle, IDrawStrategy { public void draw() { paint(); } }
class SquareDrawAdapter : Square, IDrawStrategy { public void draw() { paint(); } }

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; }
}

class Client {
    static void Main() {
        Grapher grapher = new Grapher(new TriangleDrawAdapter());
        grapher.drawShape();
        grapher.setShape(new CircleDrawAdapter());
        grapher.drawShape();
        grapher.setShape(new SquareDrawAdapter());
        grapher.drawShape();
    }
}

C# 不支援多重繼承類別,類別適配器只能繼承具體類別,導致每個具體類別都需對應一個適配器子類別,這是類別適配器在 C# 的固有限制。

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