Overview

Observer Pattern은 Observer의 목록, 즉 Observer의 목록을 객체에 등록하여 상태 변경이 있을 때마다 객체가 메소드 등을 통해 객체에게 직접 알리도록 하는 디자인 패턴입니다. . 주로 분산 이벤트 처리 시스템을 구현하는 데 사용됩니다. 발행/구독 모델이라고도 합니다.

아주 간단한 방법으로, 객체의 상태가 변경될 때 관련 객체에 알림을 보내는 디자인 패턴은 관찰자 패턴입니다.

예를 들어 기상 조건에 따라 작동해야 하는 여러 기계가 있다고 가정합니다.
기상청에서 기상자료를 구독 중이고 날씨가 업데이트되면 이를 반영하여 표시를 변경합니다.
피험자는 날씨 데이터에 입력되어 여행하고 날씨 정보를 전달합니다.

장점
변경 사항이 있어도 처리할 수 있는 유연한 객체 지향 시스템을 구축할 수 있습니다.
객체 간의 상호 의존성을 최소화할 수 있기 때문입니다. 느슨하게 결합되어 있기 때문입니다.
개방/폐쇄 원칙(개방 폐쇄 원칙)을 지킬 수 있습니다. (Open Closed Principles: Open in Expansion, 그리고 변경 사항은 반드시 닫아야 합니다.)

불리
Observer의 알림 순서를 보장할 수 없습니다.
Observer와 Subject의 관계가 잘 정의되어 있지 않으면 원하지 않는 동작이 발생할 수 있습니다.

 

Structure

https://ko.wikipedia.org/wiki/%EC%98%B5%EC%84%9C%EB%B2%84_%ED%8C%A8%ED%84%B4

 

Code Example

package com.example.design.pattern;

import java.util.ArrayList;

interface Subject {
	public void registerObserver(Observer o);

	public void removeObserver(Observer o);

	public void notifyObservers();
}

interface Observer {
	public void update(float temperature, float humidity, float pressure);
}

interface DisplayElement {
	public void display();
}

class WeatherData implements Subject {
	private ArrayList<Observer> observers;
	private float temperature;
	private float humidity;
	private float pressure;

	public WeatherData() {
		observers = new ArrayList<Observer>();
	}

	@Override
	public void registerObserver(Observer o) {
		observers.add(o);

	}

	@Override
	public void removeObserver(Observer o) {
		int i = observers.indexOf(o);
		if (i >= 0)
			observers.remove(i);
	}

	@Override
	public void notifyObservers() {
		for (int i = 0; i < observers.size(); i++) {
			Observer o = observers.get(i);
			o.update(temperature, humidity, pressure);
		}
	}

	public void measurementsChanged() {
		notifyObservers();
	}

	public void setMeasurements(float temperature, float humidity, float pressure) {
		this.temperature = temperature;
		this.humidity = humidity;
		this.pressure = pressure;
		measurementsChanged();
	}
}

class CurrentConditionDisplay implements Observer, DisplayElement {
	private float temperature;
	private float humidity;
	private Subject weatherData;

	public CurrentConditionDisplay(Subject weatherData) {
		this.weatherData = weatherData;
		weatherData.registerObserver(this);
	}

	@Override
	public void display() {
		System.out.println("CurrentConditionDisplay conditions : " + temperature + ", " + humidity);

	}

	@Override
	public void update(float temperature, float humidity, float pressure) {
		this.temperature = temperature;
		this.humidity = humidity;
		display();
	}
}

class StatisticsDisplay implements Observer, DisplayElement {
	private float temperature;
	private float humidity;
	private Subject weatherData;

	public StatisticsDisplay(Subject weatherData) {
		this.weatherData = weatherData;
		weatherData.registerObserver(this);
	}

	@Override
	public void display() {
		System.out.println("StatisticsDisplay conditions : " + temperature + ", " + humidity);

	}

	@Override
	public void update(float temperature, float humidity, float pressure) {
		this.temperature = temperature;
		this.humidity = humidity;
		display();
	}
}

public class MyObserver {
	public static void main(String[] args) {
		WeatherData weatherData = new WeatherData();

		CurrentConditionDisplay currentConditionDisplay = new CurrentConditionDisplay(weatherData);
		StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);

		weatherData.setMeasurements(80, 65, 30.f);
	}
}

 

Console Result

CurrentConditionDisplay conditions : 80.0, 65.0
StatisticsDisplay conditions : 80.0, 65.0

 

Conclusion

N/A

728x90

+ Recent posts