📌 상태가 변경되면 그 상태 변경에 따라 반응하는 구조를 구현하기 위한 패턴
observing할 메소드를 담고 있는(?) 추상클래스를 정의한다.
//Player.java public abstract class Player { private final String name; public Player(String name) { this.name = name; } public String getName() { return name; } public abstract void update(int n); }
추상클래스를 상속받는 구체적인 구현클래스를 생성한다.
//OddBettingPlayer.java public class OddBettingPlayer extends Player { public OddBettingPlayer(String name) { super(name); } @Override public void update(int n) { if (n % 2 == 1) { System.out.println(getName() + " win!"); } } } //EvenBettingPlayer.java public class EvenBettingPlayer extends Player { public EvenBettingPlayer(String name) { super(name); } @Override public void update(int n) { if (n % 2 == 0) { System.out.println(getName() + " win!"); } } }
play를 하면서 데이터 변경을 통보한다.
//DicePlay.java public class DicePlay { private final LinkedList<Player> players = new LinkedList<Player>(); private final Random random = new Random(); public void addPlayer(Player player) { players.add(player); } public void play() { int v = random.nextInt(6) + 1; System.out.println("Dice Number: " + v); for (Player player : players) { player.update(v); } } } //Main.java public class Main { public static void main(String[] args) { DicePlay dicePlay = new DicePlay(); Player player1 = new EvenBettingPlayer("Jane"); Player player2 = new OddBettingPlayer("Suji"); dicePlay.addPlayer(player1); dicePlay.addPlayer(player2); for (int i = 0; i < 10; i++) { dicePlay.play(); System.out.println(); } } }