μƒνƒœ

객체가 νŠΉμ • μƒνƒœμ— 따라 ν–‰μœ„λ₯Ό λ‹¬λ¦¬μ‚¬λŠ” μƒν™©μ—μ„œ

μžμ‹ μ΄ 직접 μƒνƒœλ₯Ό μ²΄ν¬ν•˜μ—¬ μƒνƒœμ— 따라 ν–‰μœ„λ₯Ό ν˜ΈμΆœν•˜μ§€ μ•Šκ³  μƒνƒœλ₯Ό 객체화 ν•˜μ—¬ μƒνƒœκ°€ 행동할 수 μžˆλ„λ‘ μœ„μž„ν•˜λŠ” νŒ¨ν„΄ 을 λ§ν•œλ‹€.

μƒνƒœ νŒ¨ν„΄

μ‚¬μš©μ˜ˆ

  • 상황
    • λ…ΈνŠΈλΆ 전원을 켜고 λ„λŠ” 상황
  • μƒνƒœ
    • λ…ΈνŠΈλΆ 켜짐 μƒνƒœ
    • λ…ΈνŠΈλΆ 꺼짐 μƒνƒœ
  • λ™μž‘
    • μ „μ›λ²„νŠΌμ„ λˆ„λ¦„

Laptop.class

public class Laptop {
  public static String ON = "on";
  public static String OFF = "off";

  public static String powerState = "";

  public Laptop() {
    setPowerState(Laptop.OFF);
  }

  public void setPowerState(String powerState) {
    this.powerState = powerState;
  }

  public void powerPush() {
    if ("on".equals(this.powerState)) {
      System.out.println("전원 OFF");
    } else if ("saving".equals(this.powerState)) {
      System.out.println("전원 ON");
    } else {
      System.out.println("μ ˆμ „ λͺ¨λ“œ");
    }
  }
}

μœ„ μ½”λ“œμ—μ„œ 보면 μ œν’ˆ ꡬ뢄별 (Laptop 이 μ•„λ‹Œ TV λ‚˜ Radio 와 같은) 이 μΆ”κ°€λ λ•Œ μ‘°κ±΄λ“€κΉŒμ§€ μˆ˜μ •ν•΄μ•Όλ˜λŠ” λ²”μœ„κ°€ λ„“κΈ° λ•Œλ¬Έμ— λΆ„κΈ°λ¬Έλ§ˆλ‹€ 일일이 μˆ˜μ •μ΄ μ–΄λ ΅λ‹€.
λ”°λΌμ„œ μƒνƒœλ‘œ κ΄€λ¦¬ν•˜λŠ”κ²ƒμ΄ μ’‹λ‹€.

전원 μƒνƒœλ₯Ό μΊ‘μŠν™”ν•œ μΈν„°νŽ˜μ΄μŠ€λ₯Ό μ„€μ •

public interface PowerState {
  public void powerPush();
}

PowerState μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν•œ 각 μƒνƒœ 클래슀λ₯Ό μ„€μ •

public class On implements PowerState {
  @Override
  public void powerPush() {
    System.out.println("전원 ON")
  }
}
public class Off implements PowerState {
  @Override
  public void powerPush() {
    System.out.println("전원 OFF")
  }
}
public class Saving implements PowerState {
  @Override
  public void powerPush() {
    System.out.println("μ ˆμ „ λͺ¨λ“œ");
  }
}

Laptop 클래슀λ₯Ό μ•Œλ§žκ²Œ μˆ˜μ •

public class Laptop {
  private PowerState powerState;

  public Laptop() {
    this.powerState = new Off();
  }

  public void setPowerState(PowerState powerState) {
    this.powerState = powerState;
  }

  public void powerPush() {
    powerState.powerPush();
  }
}

이λ₯Ό μ‚¬μš©ν•  ν΄λΌμ΄μ–ΈνŠΈ μ½”λ“œλ₯Ό μž‘μ„±










Β 

Β 

Β 




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

    On on = new On();
    Off off = new Off();
    Saving saving = new Saving();

    laptop.powerPush();
    laptop.setPowerState(on);
    laptop.powerPush();
    laptop.setPowerState(saving);
    laptop.powerPush();
    laptop.setPowerState(off);
    laptop.powerPush();
  }
}

참고자료

https://victorydntmd.tistory.com/294