์ „๋žต

๊ฐ์ฒด๋“ค์ด ํ•  ์ˆ˜ ์žˆ๋Š” ํ–‰์œ„ ๊ฐ๊ฐ์— ๋Œ€ํ•ด ์ „๋žต ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ , ์œ ์‚ฌํ•œ ํ–‰์œ„๋“ค์„ ์บก์Šํ™” ํ•˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ •์˜ ํ•˜์—ฌ
ํ–‰์œ„๋ฅผ ๋ฐ”๊พธ๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ ์ง์ ‘์ ์œผ๋กœ ํ–‰์œ„๋ฅผ ์ˆ˜ํ–‰ํ•˜์ง€ ์•Š๊ณ  ์ „๋žต์„ ๋ฐ”๊ฟ”์คŒ์œผ๋กœ์„œ ํ–‰์œ„๋ฅผ ์œ ์—ฐํ•˜๊ฒŒ ํ™•์žฅ ์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

๋””์ž์ธ ํŒจํ„ด์˜ ๊ฐ€์žฅ ์ค‘์š”ํ•œ ํŒจํ„ด์œผ๋กœ ๋‹ค์Œ 3๊ฐ€์ง€์˜ ์š”์†Œ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค.

์ „๋žต๊ฐ์ฒด๋ฅผ ๊ฐ€์ง„ ์ „๋žต ๊ฐ์ฒด

public interface Action {
    void move();
}

์ „๋žต ๊ฐ์ฒด์˜ ๊ตฌํ˜„

public class Walking implements Action {
  @Override
  public void move() {
    System.out.println("Walking road");
  }
}
public class Running implements Action {
  @Override
  public void move() {
    System.out.println("Running road");
  }
}

์ „๋žต ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ปจํ…์ŠคํŠธ (์†Œ๋น„)

public class Human {
  void start(Action action) {
    System.out.println("Start Action");
    action.move();
    System.out.println("End Action");
  }
}

์ „๋žต ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด ์ปจํ…์ŠคํŠธ์— ์ฃผ์ž…ํ•˜๋Š” ํด๋ผ์ด์–ธํŠธ (๊ณต๊ธ‰)

public class Client {
  public static void main (String[] args) {
    Human human = new Human();

    Walking walk = new Walking();
    human.start(walk);

    Running run = new Running();
    human.start(run);
  }
}
Start Action
Walking road
End Action
Start Action
Running road
End Action

ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ „๋žต์„ ์ƒ์„ฑํ•˜์—ฌ ์ „๋žต์„ ์‹คํ–‰ (์†Œ๋น„) ํ•  ์ปจํ…์ŠคํŠธ์—๊ฒŒ ์ฃผ์ž…ํ•˜๋Š” ํŒจํ„ด์ด๋‹ค.

ํ…œํ”Œ๋ฆฟ ๋ฉ”์†Œ๋“œ ํŒจํ„ด๊ณผ ์œ ์‚ฌํ•˜์ง€๋งŒ ๋‹ค์–‘ํ•œ ์ „๋žต์„ ๋ณ€๊ฒฝํ•˜๋ฉด์„œ ์ปจํ…์ŠคํŠธ์—๊ฒŒ ์ฃผ์ž…ํ•  ์ˆ˜ ์žˆ๋‹ค. (ํ…œํ”Œ๋ฆฟ ๋ฉ”์†Œ๋“œ๋ณด๋‹ค ์šฐ์ˆ˜)