μν
κ°μ²΄κ° νΉμ μνμ λ°λΌ νμλ₯Ό λ¬λ¦¬μ¬λ μν©μμ
μμ μ΄ μ§μ μνλ₯Ό 체ν¬νμ¬ μνμ λ°λΌ νμλ₯Ό νΈμΆνμ§ μκ³ μνλ₯Ό κ°μ²΄ν νμ¬ μνκ° νλν μ μλλ‘ μμνλ ν¨ν΄ μ λ§νλ€.
μ¬μ©μ
- μν©
- λ ΈνΈλΆ μ μμ μΌκ³ λλ μν©
- μν
- λ ΈνΈλΆ μΌμ§ μν
- λ ΈνΈλΆ κΊΌμ§ μν
- λμ
- μ μλ²νΌμ λλ¦
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();
}
}
μ°Έκ³ μλ£