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

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

     編輯:關於C語言

Strategy Pattern C# Generics 實現:編譯期類型安全與運行期靈活結合

核心代碼


interface IDrawStrategy { void draw(); }

class Grapher where T : class, IDrawStrategy, new() {
    private T _drawStrategy = default(T);
    public Grapher() { _drawStrategy = new T(); }
    public void drawShape() { if (_drawStrategy != null) _drawStrategy.draw(); }
    public void setShape(T 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();
        grapher.drawShape();
        Grapher grapher2 = new Grapher();
        grapher2.drawShape();
    }
}

執行結果


Draw Square
Draw Circle

關鍵差異分析

維度Strategy (OOP)Template MethodGenerics
多態實現介面 + 動態繫結 (運行期)繼承 + 重寫 (編譯期)泛型約束 (編譯期)
運行期變換支援 (setShape)不支援不支援 (類型參數固定)
效能虛擬呼叫開銷虛擬呼叫開銷零開銷 (靜態調度)

GoF 原文:Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.

Known Use:Eclipse Plugin 架構,無需修改核心即可擴充功能。

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