using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObserverPattern : MonoBehaviour {
void Start () {
WeatherData data = new WeatherData();
CurrentConditionDisplay conditionDisplay = new CurrentConditionDisplay(data);
data.SetMeasurements(123, 456, 789);
data.SetMeasurements(1233, 4566, 7899);
conditionDisplay.RemoveObserver();
data.SetMeasurements(12133, 45166, 78919);
}
}
public class CurrentConditionDisplay : DisplayElement,Observer{
private float temp;
private float humi;
public Subject weather;
public CurrentConditionDisplay(Subject data){
this.weather = data;
this.weather.RegisterObserver(this);
}
public void RemoveObserver()
{
this.weather.RomoveObserver(this);
}
public void Update(float temp, float humidity, float pressure){
this.temp = temp;
this.humi = humidity;
Display();
}
public void Display(){
Debug.Log("temp = " + temp + " humi = " + humi);
}
}
public class WeatherData : Subject{
private List<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData(){
observers = new List<Observer>();
}
public void RegisterObserver(Observer observer){
observers.Add(observer);
}
public void RomoveObserver(Observer observer){
int index = observers.IndexOf(observer);
if(index >= 0)
observers.RemoveAt(index);
}
public void NotifyObserver(){
int count = observers.Count;
for (int index = 0; index < count;index ++){
observers[index].Update(temperature,humidity,pressure);
}
}
public void MeasurementsChanged(){
NotifyObserver();
}
public void SetMeasurements(float temp,float hunm,float pressure){
this.temperature = temp;
this.pressure = pressure;
this.humidity = hunm;
MeasurementsChanged();
}
}
public interface Subject {
void RegisterObserver(Observer observer);
void RomoveObserver(Observer observer);
void NotifyObserver();
}
public interface Observer{
void Update(float temp, float humidity, float pressure);
}
public interface DisplayElement{
void Display();
}