> For the complete documentation index, see [llms.txt](https://blakes-organization.gitbook.io/rainsister/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blakes-organization.gitbook.io/rainsister/design-pattern/strategy-pattern.md).

# Strategy Pattern

### 장점

* 코드 중복 방지 즉 달라지는 부분을 찾고 분리해 낸다.
* Runtime 시 target method 변경
* 확장성 및 알고리즘 변경 용이

### 구조

<figure><img src="/files/j7wbe1VxA8fdA4clHeLl" alt=""><figcaption></figcaption></figure>

### 예시코드

```java
public interface Pay {
    void action();
}
```

```java
public class KakaoPayService implements Pay{
    @Override
    public void action() {
        System.out.println("카카오페이로 지불합니다.");
    }
}
```

```java
public class NaverPayService implements Pay {

    @Override
    public void action() {
        System.out.println("네이버페이로 지불합니다.");
    }
}
```

```java
public class WechatPayService implements Pay {

    @Override
    public void action() {
        System.out.println("위챗페이로 지불합니다.");
    }
}
```

```java
public class BuyItem {
    private Pay pay ;

    public BuyItem(Pay pay){
        this.pay = pay;
    }
    public void payAction(){
        pay.action();
    }
    public void setPay(Pay pay){
        this.pay = pay;
    }
}
```

```java
public class Main {
    public static void main(String[] args) {
        System.out.println("======지불 해보겠습니다!");

        BuyItem buyItem = new BuyItem(new KakaoPayService());
        buyItem.payAction();

        BuyItem buyItem2 = new BuyItem(new NaverPayService());
        buyItem2.payAction();

        BuyItem buyItem3 = new BuyItem(new WechatPayService());
        buyItem3.payAction();
    }
}
```

[소스코드](https://github.com/luxury515/design-pattern-demo/tree/master/StratelgyPattern)
