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

我的設計模式之旅[7]:運用泛型改良 Adapter Pattern C# Generics 組合方式 (上)

     編輯:關於C語言

C# Generics 不支援繼承泛型參數(class DrawAdapter<T> : T 錯誤:Cannot derive from 'T' because it is a type parameter),故採組合方式改良類別適配器。

C# 組合泛型實作

class DrawAdapter<T> : IDrawStrategy where T : IPaint, new() {
    protected T _adaptee = new T();
    public void draw() { _adaptee.paint(); }
}

完整程式碼

using System;

interface IDrawStrategy { void draw(); }
interface IPaint { void paint(); }

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

class DrawAdapter<T> : IDrawStrategy where T : IPaint, new() {
    protected T _adaptee = new T();
    public void draw() { _adaptee.paint(); }
}

class Client {
    static void Main() {
        Grapher grapher = new Grapher(new DrawAdapter<Triangle>());
        grapher.drawShape();
        grapher.setShape(new DrawAdapter<Circle>());
        grapher.drawShape();
        grapher.setShape(new DrawAdapter<Square>());
        grapher.drawShape();
    }
}

執行結果

Draw Triangle
Draw Circle
Draw Square

單一 DrawAdapter<T> 取代三個具體適配器類別,客戶端以 new DrawAdapter<Triangle>() 指定具體型別,達到類別適配器「單一類別適配多型別」的效果,且保有型別安全。

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