Work & Programming/System Design

[Structural Pattern] - Decorator

자전거통학 2024. 5. 15. 10:28

https://refactoring.guru/design-patterns/decorator

 

Decorator

/ Design Patterns / Structural Patterns Decorator Also known as: Wrapper Intent Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors. Prob

refactoring.guru

 

 

특정 기본 행위 위에 별도로 특정 행위를 추가적으로 하고자 할 때 사용.

예시 

 - Lobby Card Renderer : 기본 카드를 그리고, 그 위에 추가 정보, tag 등을 필요에 따라 덧추가 한다.

 

예시 코드 

더보기
public class Card
{
    public virtual void Refresh() 
    { 
        Console.WriteLine("Card itself");
    }
}

public class CardHitDecorator : Card
{
    Card _card;

    public CardHitDecorator(Card card) { _card = card; }
    public override void Refresh()
    {
        // do its own thing. 
        //
        // 
        Console.WriteLine("Hit Deco");
        if(_card != null)
            _card.Refresh();
    }
}
public class CardRotationDecorator : Card
{
    Card _card;

    public CardRotationDecorator(Card card) { _card = card; }
    public override void Refresh()
    {
        // do its own thing. 
        //
        // 
        Console.WriteLine("Rot Deco");
        if(_card != null)
            _card.Refresh();
    }
}


internal class DecoratorDemo
{
    public void Run()
    {
        Card lobbyCard = new Card();

        CardRotationDecorator rotDeco = new CardRotationDecorator(new CardHitDecorator(lobbyCard));
        rotDeco.Refresh();
    }
}

'Work & Programming > System Design' 카테고리의 다른 글

[Structural Pattern] - Flyweight  (0) 2024.05.15
[Structural Pattern] - Facade  (0) 2024.05.15
[Structural Pattern] - Composite  (0) 2024.05.15
[Structural Pattern] - Adapter  (0) 2024.05.15
[Creational Pattern] - Singleton  (0) 2024.05.15