0

この例がアダプタ パターンの意図を満たしているかどうかを知る必要があります。

この例は、 Pluggable Adapterパターンを満たすことを目的としていますが、次の 2 つのインターフェイスを適応させています。

interface ITargetOld {
    double Precise(double i);
}

interface ITargetNew {
    string RoundEstimate(int i);
} 

public class Adapter : ITargetOld, ITargetNew {
    public double Precise(double i) {
        return i / 3;
    }

    public string RoundEstimate(int i) {
        return Math.Round(Precise(i)).ToString();
    }

    public string NewPrecise(int i) {
        return Precise(Convert.ToInt64(i)).ToString();
    }
}

クライアントは次のようになります。

class Program {
    static void Main(string[] args) {
        ITargetOld adapter1 = new Adapter();
        Console.WriteLine("Old division format (Precise) " + adapter1.Precise(5));

        ITargetNew adapter2 = new Adapter();
        Console.WriteLine("New division format (Round Estimate) " + adapter2.RoundEstimate(5));

        Adapter adapter3 = new Adapter();
        Console.WriteLine("New Precise format " + adapter3.NewPrecise(5));

        Console.ReadKey();
    }
}

ラファエル

4

1 に答える 1

1

私にとって、あなたのコードは実際にはアダプターではありません。アダプター パターンでは、型 A のオブジェクトがあり、型 B を必要とするコードでそれを使用する場合について説明します。

interface A {
    method doSmthA();
}

interface B {
    method doSmthB();
}

class AdapterAToB implements B{
    private A a;
    constructor AdapterAToB(A a) {
         this.a = a;
    }

    method doSmthB() {
         a.doSomthA();
    }
}

上記のケースでは、タイプ A のオブジェクトをインターフェイス B に変換し、B のインスタンスが必要な場所でそれを使用できます。

于 2013-05-15T17:25:47.043 に答える