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

我的設計模式之旅[4]:運用 C# Generic 改良 Strategy Pattern (上)

     編輯:關於C語言

系列第四篇開啟 C# 版本探討。C# 2.0 引入 Generics,嘗試將 C++ Template 版 Strategy Pattern 移植。核心概念相同:為讓策略完整存取 Context 物件,將 this 傳給策略的 draw() 方法。

初版介面設計(未泛型化)

interface IShape {
    void draw(Grapher grapher);
}

Grapher 持有 IShape 參考,drawShape() 呼叫 shape.draw(this)。策略類別(Triangle、Circle、Square)實作 IShape,在 draw() 中取得 grapher.getText()。

完整程式碼

程式碼截圖
using System;

interface IShape {
    void draw(Grapher grapher);
}

class Grapher {
    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 {
    public void draw(Grapher grapher) {
        Console.WriteLine("Draw {0:s} in Triangle", grapher.getText());
    }
}
class Circle : IShape {
    public void draw(Grapher grapher) {
        Console.WriteLine("Draw {0:s} in Circle", grapher.getText());
    }
}
class Square : IShape {
    public void draw(Grapher grapher) {
        Console.WriteLine("Draw {0:s} in Square", grapher.getText());
    }
}

class MainClass {
    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 仍綁定 Grapher 型別,若新增 Painter 類別欲複用策略將無法編譯。下篇將引入 Generic 解決。

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