State Pattern - dnwls16071/Backend_Summary GitHub Wiki

πŸ“š State Pattern μ„€λͺ…

  • λ¬΄μ–Έκ°€μ˜ 'μƒνƒœ'κ°€ 각각에 ν•΄λ‹Ήν•˜λŠ” 클래슀의 객체둜 μ‘΄μž¬ν•œλ‹€.
  • 객체의 λ‚΄λΆ€ μƒνƒœμ— 따라 행동이 달라져야 ν•  λ•Œ, 그리고 μƒνƒœκ°€ 자주 변경될 λ•Œ μ‚¬μš©ν•˜κΈ° μ ν•©ν•˜λ‹€.

[Ex1]

public interface State {
    void open(Door door);
    void close(Door door);
}
// 문이 λ‹«νžŒ μƒνƒœ
public class ClosedState implements State {
    @Override
    public void open(Door door) {
        System.out.println("Door is now Open.");
        door.setState(new OpenState());
    }

    @Override
    public void close(Door door) {
        System.out.println("Door is already Closed.");
    }
}

// 문이 μ—΄λ¦° μƒνƒœ
public class OpenState implements State {
    @Override
    public void open(Door door) {
        System.out.println("Door is already Open.");
    }

    @Override
    public void close(Door door) {
        System.out.println("Door is now Closed.");
        door.setState(new ClosedState());
    }
}
public class Door {

    private State state;  // μƒνƒœλ₯Ό λ©€λ²„λ³€μˆ˜λ‘œ κ°€μ§„λ‹€.
    public Door() {
        this.state = new ClosedState();
    }

    public void setState(State state) {
        this.state = state;
    }

    public void open() {
        state.open(this);
    }
    public void close() {
        state.close(this);
    }
}

[Ex2]

public interface State {
    void play(VideoPlayer player);
    void stop(VideoPlayer player);
}
public class StoppedState implements State {
    @Override
    public void play(VideoPlayer player) {
        System.out.println("Starting the video.");
        player.setState(new PlayingState());
    }

    @Override
    public void stop(VideoPlayer player) {
        System.out.println("Video is already stopped.");
    }
}

// ν”Œλ ˆμ΄ μƒνƒœ
public class PlayingState implements State {
    @Override
    public void play(VideoPlayer player) {
        System.out.println("Video is already playing.");
    }

    @Override
    public void stop(VideoPlayer player) {
        System.out.println("Pausing the video.");
        player.setState(new PausedState());
    }
}

// μ •μ§€ μƒνƒœ
public class PausedState implements State {
    @Override
    public void play(VideoPlayer player) {
        System.out.println("Resuming the video.");
        player.setState(new PlayingState());
    }

    @Override
    public void stop(VideoPlayer player) {
        System.out.println("Stopping the video.");
        player.setState(new StoppedState());
    }
}
public class VideoPlayer {
    private State state;   // μƒνƒœλ₯Ό ν•„λ“œλ‘œ κ°€μ§„λ‹€.

    public VideoPlayer() {
        // Set initial state Stopped
        this.state = new StoppedState();
    }

    public void setState(State state) {
        this.state = state;
    }

    public void play() {
        state.play(this);
    }

    public void stop() {
        state.stop(this);
    }
}