2012-05-01 3 views
2

에서 포장 오브젝트 액세스 값은 내가데코레이터 패턴 - 장식

는이 코드가 있다고 가정하자 데코레이터 패턴에 대한 질문이

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?"))); 
    } 
} 

우리는 두 장식 래핑하는 클래스라는 환상을 가지고 AAA와 BBB

어떻게 최상의 액세스

내가 노력 AAA 나 BBB

에서 문자열 값 (것입니다) "CanSeeThisValue는"기본 (CL)을 만들 수 있습니다 그들 모두를위한 엉덩이,하지만 그들은 같은 기지를 공유하는 동안 그들은 기지의 동일한 인스턴스를 공유하지 않습니다

대신 각 생성자에 값을 전달해야합니까?

+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; 
    } 

    ... 

} 
관련 문제