티스토리 뷰

Programming/디자인 패턴

Observer Pattern

Albothyl 2019. 1. 24. 15:13

Observer Pattern

 객체의 상태 변화를 관찰하는 관찰자들, 즉 옵저버들의 목록을 객체에 등록하여 상태 변화가 있을 때마다 메소드 등을 통해 객체가 직접 목록의 각 옵저버에게 통지하도록 하는 패턴이다. 주로 분산 이벤트 핸들링 시스템을 구현하는 데 사용된다. pubish/subscribe 패턴으로 알려져 있기도 하다.

- 특정 인스턴스에 특정 인터페이스를 구현하는 클레스를 등록한다.

- 특정 인스턴스에서 등록된 클레스의 인터페이스의 메소드를 호출한다.





public class Orcs implements WeatherObserver {

  @Override

  public void update(WeatherType currentWeather) {

    switch (currentWeather) {

      case COLD:

        System.out.println("The orcs are freezing cold.");

        break;

      case RAINY:

        System.out.println("The orcs are dripping wet.");

        break;

      case SUNNY:

        System.out.println("The sun hurts the orcs' eyes.");

        break;

      case WINDY:

        System.out.println("The orc smell almost vanishes in the wind.");

        break;

      default:

        break;

    }

  }

}



public class Hobbits implements WeatherObserver {

  @Override

  public void update(WeatherType currentWeather) {

    switch (currentWeather) {

      case COLD:

        System.out.println("The hobbits are shivering in the cold weather.");

        break;

      case RAINY:

        System.out.println("The hobbits look for cover from the rain.");

        break;

      case SUNNY:

        System.out.println("The happy hobbits bade in the warm sun.");

        break;

      case WINDY:

        System.out.println("The hobbits hold their hats tightly in the windy weather.");

        break;

      default:

        break;

    }

  }

}



public interface WeatherObserver {

  void update(WeatherType currentWeather);

}



public enum WeatherType {

  SUNNY, RAINY, WINDY, COLD;

}



public class Weather {

  private WeatherType currentWeather;

  private List<WeatherObserver> observers;


  public Weather() {

    observers = new ArrayList<>();

    currentWeather = WeatherType.SUNNY;

  }


  public void addObserver(WeatherObserver obs) {

    observers.add(obs);

  }


  public void removeObserver(WeatherObserver obs) {

    observers.remove(obs);

  }


  public void timePasses() {

    WeatherType[] enumValues = WeatherType.values();

    currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];

    System.out.println("The weather changed to {}.", currentWeather);

    notifyObservers();

  }


  private void notifyObservers() {

    for (WeatherObserver observer : observers) {

      observer.update(currentWeather);

    }

  }

}



public class App {

  public static void main(String[] args) {


    Weather weather = new Weather();

    weather.addObserver(new Orcs());

    weather.addObserver(new Hobbits());


    weather.timePasses();

    weather.timePasses();

    weather.timePasses();

    weather.timePasses();


    System.out.println("--Running generic version--");

    GWeather gWeather = new GWeather();

    gWeather.addObserver(new GOrcs());

    gWeather.addObserver(new GHobbits());


    gWeather.timePasses();

    gWeather.timePasses();

    gWeather.timePasses();

    gWeather.timePasses();

  }

}

'Programming > 디자인 패턴' 카테고리의 다른 글

Factory Method Pattern  (0) 2019.01.24
Builder Pattern  (0) 2019.01.24
Template Method Pattern  (0) 2019.01.24
Strategy Pattern  (0) 2019.01.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함