One_KWS

스트래티지 패턴(Strategy Pattern) 본문

디자인 패턴

스트래티지 패턴(Strategy Pattern)

One-Kim 2023. 4. 13. 21:22

소개

스트래티지 패턴(Strategy Pattern)은 행위를 클래스로 캡슐화하여 동적으로 행위를 자유롭게 바꿀 수 있게 해주는 패턴이다. 같은 문제를 해결하는 여러 알고리즘이 클래스별로 캡슐화되어 있고 이들이 필요할 때 교체할 수 있도록 함으로써 동일한 문제를 다른 알고리즘으로 해결할 수 있다. 스트래티지 패턴을 이용하면 수정이 필요한 부분을 최소화할 수 있다.

 

스트래티지 패턴은 아래와 상황에서 사용할 수 있다.

  • 비슷한 작업을 하는 알고리즘이 여러 개 존재할 경우
  • 알고리즘을 사용하는 클라이언트 코드와 알고리즘의 구현 코드를 분리하고 싶을 경우
  • 알고리즘을 쉽게 교체하거나 확장하고 싶을 경우

 

Strategy Pattern

 

Strategy

Strategy 인터페이스에서는 알고리즘을 정의하는 메서드를 포함한다.

public interface Strategy {
    public void Execute();
}

 

ConcreteStrategy

ConcreteStrategy 클래스에서는 Strategy 인터페이스를 구현한다. 

class ConcreteStrategyA : Strategy {
    public void Execute() {
        Console.WriteLine("Strategy A Execute \n");
    }
}

class ConcreteStrategyB : Strategy {
    public void Execute() {
        Console.WriteLine("Strategy B Execute \n");
    }
}

class ConcreteStrategyC : Strategy {
    public void Execute() {
        Console.WriteLine("Strategy C Execute \n");
    }
}

 

Context

Context 클래스는 Strategy 인터페이스를 사용한다. Strategy 객체를 설정하고 실행한다.

class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void Execute() {
        strategy.Execute();
    }
}

 

실행 

메인 함수에서 Context 객체를 선언하고 Strategy를 설정하여 Execute 메서드를 실행한다.

class Program {
    static void Main(string[] args) {
        Context context;

        context = new Context(new ConcreteStrategyA());
        context.Execute();

        context = new Context(new ConcreteStrategyB());
        context.Execute();

        context = new Context(new ConcreteStrategyC());
        context.Execute();
    }
}

'디자인 패턴' 카테고리의 다른 글

커맨드 패턴(Command Pattern)  (0) 2023.04.10
추상 팩토리 패턴 (Abstract Factory Pattern)  (0) 2022.06.08