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

我的 Design Pattern 之旅 [1]:Strategy Pattern (5) - C# Delegate 實現

     編輯:關於C語言

Strategy Pattern C# Delegate 實現:函數指標與觀察者模式的語言級融合

核心代碼


class Grapher {
    private DrawDelegate _drawDelegate = null;
    public delegate void DrawDelegate();
    public Grapher() {}
    public Grapher(DrawDelegate drawDelegate) { _drawDelegate = drawDelegate; }
    public void drawShape() { if (_drawDelegate != null) _drawDelegate(); }
    public void setShape(DrawDelegate drawDelegate) { _drawDelegate = drawDelegate; }
}

class Triangle { public static void draw() { Console.WriteLine("Draw Triangle"); } }
class Circle { public static void draw() { Console.WriteLine("Draw Circle"); } }
class Square { public static void draw() { Console.WriteLine("Draw Square"); } }

class Program {
    public static void Main() {
        Grapher grapher = new Grapher(Square.draw);
        grapher.drawShape();
        grapher.setShape(Circle.draw);
        grapher.drawShape();
    }
}

執行結果


Draw Square
Draw Circle

Delegate 是 C# 對函數指標與觀察者模式的語言級實現,天然適合 Strategy Pattern。GoF 也展示 Template Method 實現 Strategy。

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