노현진's Blog

Strategy Pattern

Strategy Pattern에 대해 설명하는 페이지입니다.

Posted
Preview Image
By HyunJinNo

Tags

Design Pattern, Java

1. Introduction

  • Purpose
    • Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior.
  • Use When
    • The only difference between many related classes is their behavior.
    • Multiple versions or variations of an algorithm are required.
    • The behavior of a class should be defined at runtime.
    • Conditional statements are complex and hard to maintain.

2. How to Use (Example)

java
1public interface FlyBehavior {
2    public void fly();
3}
4
5public class FlyWithWings implements FlyBehavior {
6    public void fly() {
7        System.out.println("I'm flying.");
8    }
9}
10
11public class FlyNoWay implements FlyBehavior {
12    public void fly() {
13        System.out.println("I can't fly.");
14    }
15}
java
1public abstract class Bird {
2    FlyBehavior flyBehavior;
3
4    public Bird() {}
5
6    public void performFly() {
7        flyBehavior.fly();
8    }
9}
10
11public class MyBird extends Bird {
12    public MyBird() {
13        flyBehavior = new FlyNoWay();
14    }
15
16    public void setFlyBehavior(FlyBehavior flyBehavior) {
17        this.flyBehavior = flyBehavior();
18    }
19}
java
1public class Main {
2    public static void main(String[] args) {
3        Bird myBird = new MyBird();
4        myBird.performFly();  // "I can't fly."
5
6        myBird.setFlyBehavior(new FlyWithWings());
7        myBird.performFly();  // "I'm flying."
8    }
9}

© HyunJinNo. Some rights reserved.