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

我的 Design Pattern 之旅 [1]:Strategy Pattern (3) - C# Interface 經典實現

     編輯:關於C語言

Strategy Pattern C# 經典介面實現:最標準的 OOP 多態寫法

核心代碼


interface IDrawStrategy { void draw(); }

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

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

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

執行結果


Draw Square
Draw Circle

介面是最正規 OOP 寫法。Effective C++ Item 35 亦使用函數指標實現 Strategy,屬 C/C++ 獨有寫法。

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