带有接口的观察者模式中的delphi AV

时间:2013-12-16 16:23:08

标签: delphi delphi-xe observer-pattern access-violation

我想用Delphi实现观察者模式。 这是一个接口ISubject和一个实现观察者的类TWeatherData

ISubject = interface
    procedure notifyObservers;
    procedure removeObserver(o: IObserver);
    procedure registerObserver(o: IObserver);
  end;

TWeatherData = class(TInterfacedObject, ISubject)
  private
    observers: TList;
    FTemperature: Double;
    FHumidity: Double;
    FPressure: Double;
  public
    // ...
    procedure notifyObservers;
    procedure setMeasurements(ATemperature, AHumidity, APressure: Double);
  end;

TWeatherData.notifyObservers执行时,我收到访问冲突关于读取地址

procedure TWeatherData.notifyObservers;
var
  observer: ^IObserver;
begin
  for observer in observers do
    observer.Update(FTemperature, FHumidity, FPressure); //oops -> there raised AV.
end;


procedure TWeatherData.setMeasurements(ATemperature, AHumidity,
  APressure: Double);
begin
  measurementsChanged; // and this one calls TWeatherData.notifyObservers;
end;

主程序:

    weatherStation := TWeatherData.Create;
    currentConditionalDisplay := TCurrentConditionalDisplay.Create(weatherStation);
    weatherStation.setMeasurements(100.0, 58.0, 756.0); // a stack head of exception.

1 个答案:

答案 0 :(得分:5)

AV被引发,因为您只存储指向IObserver的指针。但这是一个弱引用,Observer-Instance已经消失了。

使用TList<IObserver>代替Nicks blog

如果您不想使用Generics,那么您应该使用TInterfaceList here