# 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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blakes-organization.gitbook.io/rainsister/design-pattern/strategy-pattern.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
