首先有一个更新天气布告板的系统。
public class ConditionsPanel{
public void update(float temp, float humidity, float pressure){
Debug.Log ("ConditionsPanel");
Debug.Log ("temp: " + temp);
Debug.Log ("humidity: " + temp);
Debug.Log ("pressure: " + temp);
}
}
public class StatisticsPanel{
public void update(float temp, float humidity, float pressure){
Debug.Log ("StatisticsPanel");
Debug.Log ("temp: " + temp);
Debug.Log ("humidity: " + temp);
Debug.Log ("pressure: " + temp);
}
}
public class ForecastPanel{
public void update(float temp, float humidity, float pressure){
Debug.Log ("ForecastPanel");
Debug.Log ("temp: " + temp);
Debug.Log ("humidity: " + temp);
Debug.Log ("pressure: " + temp);
}
}
public class WeatherData{
public ConditionsPanel conditionsDisplay = new ConditionsPanel();
public StatisticsPanel statisticsDisplay = new StatisticsPanel();
public ForecastPanel forecastPanel = new ForecastPanel();
public float getTemperature(){
return 1.0f;
}
public float getHumidity(){
return 2.0f;
}
public float getPressure(){
return 3.0f;
}
public void mentsChanged(){
float temp = getTemperature ();
float humidity = getHumidity ();
float pressure = getPressure ();
conditionsDisplay.update (temp, humidity, pressure);
statisticsDisplay.update (temp, humidity, pressure);
forecastPanel.update (temp, humidity, pressure);
}
}
注意到气象站提供getter方法供各种布告板使用,这里有3个布告板。
也就是一对多的关系。
更新布告板时,是针对具体实现编程,这将导致以后增加或者删除布告板时,需要修改或者代码。
当我们需要增加公告板时,除了要添加新的公告板类外,还需要修改WeatherDate的mentsChanged方法,公告板越来越多时,这段代码也会越来越冗长,稍有变动便要修改或删除。(两者耦合过紧,一方改动牵动着另一方)
公告板接收的参数是一样的,可以考虑整合。
//主题
public interface Subject{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObserver();
}
//气象站
public class WeatherData : Subject{
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData(){
observers = new ArrayList ();
}
//注册
public void registerObserver(Observer o){
observers.Add (o);
}
//移除
public void removeObserver(Observer o){
int i = observers.IndexOf (o);
if (i > 0) {
observers.Remove(i);
}
}
//通知
public void notifyObserver(){
foreach (Observer o in observers) {
o.update(temperature, humidity, pressure);
}
}
public void measurementsChanged(){
notifyObserver ();
}
}
//观察者
public interface Observer{
void update(float temp, float humidity, float pressure);
}
//布告板
public class ConditionsPanel : Observer{
private float temperature;
private Subject weatherData;
//构造函数保存subject,并且注册自己
public ConditionsPanel(Subject weatherData){
this.weatherData = weatherData;
weatherData.registerObserver (this);
}
//观察者接口规定每个布告板都必须实现的统一接口
public void update(float temperature, float humidity, float pressure){
this.temperature = temperature;
}
}
设计原则:
1.低耦合
为了交互对象之间的松耦合设计而努力。 针对接口编程让对象之间的依赖降低,达到松耦合的目的。
2.封装变化
3.针对接口编程,不针对实现编程
4.多用组合,少用继承