public interface ISubject
{
void registerObserver(IObserver o);
void removeObserver(IObserver o);
void noifyObservers();
}
和
public interface IObserver
{
void update(float temp, float humidity, float pressure);
}
這裏是類
public class CurrentConditionsDisplay : IObserver
public float temperature;
public float humidity;
public ISubject weatherData;
public CurrentConditionsDisplay(ISubject weatherData)
{
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
}
registerObserver函數的參數是IObserver但在構造函數中使用:
weatherData.registerObserver(this);
「this」是什麼意思?我知道「this」關鍵字指的是類的當前實例,但在這種情況下,「this」關鍵字的含義是什麼?
完全一樣。您將'this'作爲參數傳遞給'registerObserver'方法。 –
這裏是正在執行構造函數的CurrentConditionsDisplay實例。 – Adil
「CurrentConditionsDisplay」由其構造函數實例化,該構造函數也將其自身傳遞給'weatherData.registerObserver'方法。您可以在該方法中傳遞'CurrentConditionsDisplay',因爲它實現了'IObserver'接口。 – navigator