공부/디자인 패턴

[공부/디자인 패턴] Strategy 패턴

오잎 클로버 2022. 3. 16. 08:20
728x90

Strategy Pattern

알고리즘의 인터페이스를 정의하고, 각각의 인터페이스를 캡슐화하여 동적으로 교체 사용 가능하도록

구현하는 디자인 패턴입니다. 클라이언트와는 독립적으로 구현되기에 새로운 알고리즘을 추가하거나

기존의 알고리즘을 쉽게 변경할 수 있습니다.

Strategy Pattern Structure

전략 패턴 구조 이미지

  • Context: 실제 각각의 알고리즘에 대한 인스턴스를 가진다.
  • Interface: 각각의 알고리즘을 가져야할 공통적인 인터페이스
  • Algorithm1, Algorithm2: 실제 인터페이스 구현. 각각의 알고리즘을 구현

예제 코드

public interface PersonInterface {
    
    void action();
    
}

PersonInterface로 공통 인터페이스인 #action을 가집니다.

public class Jumper implements PersonInterface {

    @Override
    public void action() {
        System.out.println("이동한다.");
    }
}

Jumper 클래스로 PersonInterface를 구현합니다.

(점퍼는 순간이동을 하니, #action에서 이동을 합니다.)

public class Runner implements PersonInterface {

    @Override
    public void action() {
        System.out.println("달린다.");
    }
}

그리고 Runner 클래스는 달리는 기능을 수행합니다.

 

위 Jumper와 Runner 클래스는 Algorithm에 포함됩니다.

public class Person {

    private PersonInterface person;

    public Person(PersonInterface person) {
        this.person = person;
    }

    public void action() {
        person.action();
    }

    public void changeAction(PersonInterface personInterface) {
        this.person = personInterface;
    }

}

그리고 Person은 Context에 포함되는 클래스로 실제적인 기능을 수행합니다.

public class Main {

    public static void main(String[] args) {
        Person person1 = new Person(new Jumper());
        Person person2 = new Person(new Runner());

        person1.action();
        person2.action();

        person2.changeAction(new Jumper()); // Runner 기능을 Jumper 기능으로 전환
        person2.action();
    }

}

그리고 Main 클래스는 Client을 의미하는 클래스입니다.

 

 

이상입니다.

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

[공부/디자인 패턴] Prototype 패턴  (0) 2022.03.20
[공부/디자인 패턴] Singleton 패턴  (0) 2022.03.19