2012-05-01 10 views
2

からラップされたオブジェクトでのアクセス値は、私はデコレータパターン - デコレータ

が、私はこのコードを持っていると言うことができますDecoratorパターンについて質問があり

interface IThingy 
{ 
    void Execute(); 
} 

internal class Thing : IThingy 
{ 
    public readonly string CanSeeThisValue; 

    public Thing(string canSeeThisValue) 
    { 
     CanSeeThisValue = canSeeThisValue; 
    } 

    public void Execute() 
    { 
     throw new System.NotImplementedException(); 
    } 
} 

class Aaa : IThingy 
{ 
    private readonly IThingy thingy; 

    public Aaa(IThingy thingy) 
    { 
     this.thingy = thingy; 
    } 

    public void Execute() 
    { 
     throw new System.NotImplementedException(); 
    } 
} 


class Bbb : IThingy { 
    private readonly IThingy thingy; 

    public Bbb(IThingy thingy) 
    { 
     this.thingy = thingy; 
    } 

    public void Execute() 
    { 
     throw new System.NotImplementedException(); 
    } 
} 

class Runit { 
    void Main() 
    { 
     Aaa a = new Aaa(new Bbb(new Thing("Can this be accessed in decorators?"))); 
    } 
} 

我々は2つのデコレータによってラップされたクラスと呼ばれるものを持っていますAAAとBBB

どのように私は基本CLを作ってみました、AAAまたはBBB

からのI最適なアクセス文字列値(シングである)「CanSeeThisValue」缶それらのすべてのためのお尻、しかし、彼らは同じベースを共有している間、彼らはベースの同じインスタンスを共有しません

代わりに各コンストラクタに値を渡す必要がありますか?

+1

デコレータは、彼らがラップされているものは何でものパブリック・インタフェースを使用して機能を強化、彼らは通常、その先何の知識を持っている必要があります。 –

+0

そのフィールドをベースクラスで静的にすることはできますか?または、IThingyに新しいプロパティを追加しますか?こうすることで、装飾されたクラスをループ内で使用して、そのプロパティの値を取得することができます。 –

答えて

2

デコレータは、ラッピングしているアイテムのパブリックインターフェイスに機能を追加します。あなたのデコレータがのメンバーにアクセスするためには、IThingyの部分ではない場合は、IThingyの代わりにThingをデコレータがラップする必要があるかどうかを検討する必要があります。

IThingyにはすべてCanSeeThisValueプロパティが必要な場合は、そのプロパティをIThingyインターフェイスの一部としてプロパティとして追加(および実装)します。 Thing見た目ようになるだろう

interface IThingy 
{ 
    string CanSeeThisValue { get; } 

    void Execute(); 
} 

internal class Thing : IThingy 
{ 
    public string CanSeeThisValue { get; private set; } 

    public Thing(string canSeeThisValue) 
    { 
     CanSeeThisValue = canSeeThisValue; 
    } 

    ... 

} 
関連する問題