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

我的 Design Pattern 之旅 [4]:使用 Generic 改進 Strategy Pattern (3)

     編輯:關於C語言

Generic 改進 Strategy Pattern:IGrapher 介面雙向協作與多上下文複用

核心代碼


interface IGrapher { string getText(); }

interface IShape { void draw(T grapher); }

class Grapher : IGrapher {
    private IShape shape;
    private string text;
    public Grapher() {}
    public Grapher(IShape shape) : this(shape, "Hello Shape!!") {}
    public Grapher(IShape shape, string text) { this.shape = shape; this.text = text; }
    public void drawShape() { this.shape.draw(this); }
    public void setShape(IShape shape, string text) { this.text = text; this.shape = shape; }
    public string getText() { return this.text; }
}

class Triangle : IShape where T : IGrapher {
    public void draw(T grapher) { Console.WriteLine("Draw {0:s} in Triangle", grapher.getText()); }
}
class Circle : IShape where T : IGrapher {
    public void draw(T grapher) { Console.WriteLine("Draw {0:s} in Circle", grapher.getText()); }
}
class Square : IShape where T : IGrapher {
    public void draw(T grapher) { Console.WriteLine("Draw {0:s} in Square", grapher.getText()); }
}

class main {
    public static void Main() {
        Grapher theGrapher = new Grapher(new Square());
        theGrapher.drawShape();
        theGrapher.setShape(new Circle(), "Hello C#!!");
        theGrapher.drawShape();
    }
}

執行結果


Draw Hello Shape!! in Square
Draw Hello C#!! in Circle

改進亮點

  • IShape 泛型介面,T : IGrapher 約束確保雙向協作
  • 策略可透過 grapher.getText() 取得上下文資訊
  • 若 Painter 類別也實作 IGrapher,同樣可使用 IShape 策略
  • 編譯期類型安全,運行期零裝箱開銷
完整程式碼截圖
圖 1:完整程式碼結構截圖
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved