unit Observer_Pattern;
interface
uses
Winapi.Windows,
Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs, System.Generics.Collections,Contnrs;
//Beobachter
type TObservers =
class(TObject)
public
procedure Update;
virtual;
private
end;
type TSuject =
class(TObject)
public
procedure AddObservers(Beobachter : TObservers);
virtual;
abstract;
protected
procedure NoitfyAllObserver;
virtual;
abstract;
end;
type TConcreteSubject =
class(TSuject)
private
FObserverList : TList<TObservers>;
FState : Integer;
public
procedure AddObservers(Beobachter : TObservers );
override;
procedure SetState(State : Integer);
function GetSate : Integer;
constructor Create;
destructor Destroy;
override;
protected
procedure NoitfyAllObserver;
override;
end;
type TConcreteObserver =
class(TObservers)
private
FConcreteObserver : TConcreteSubject;
public
procedure ConcreteObserver(ConcreteSubjec: TConcreteSubject);
procedure Update;
override;
abstract;
end;
implementation
{ TConcreteSubject }
procedure TConcreteSubject.AddObservers(Beobachter : TObservers);
begin
FObserverList.Add(Beobachter);
end;
constructor TConcreteSubject.Create;
begin
inherited;
FState := 0;
FObserverList := TList<TObservers>.Create;
end;
destructor TConcreteSubject.Destroy;
begin
FreeAndNil(FObserverList);
end;
function TConcreteSubject.GetSate: Integer;
begin
Result := FState;
end;
procedure TConcreteSubject.NoitfyAllObserver;
var Beobachter : TObservers;
begin
try
Beobachter := TObservers.Create;
for Beobachter
in FObserverList
do
begin
Beobachter.Update;
end;
finally
FreeAndNil(Beobachter);
end;
end;
procedure TConcreteSubject.SetState(State: Integer);
begin
FState := State;
NoitfyAllObserver;
end;
{TObservers}
procedure TObservers.Update;
begin
end;
procedure TConcreteObserver.ConcreteObserver(ConcreteSubjec: TConcreteSubject);
var Test : TObservers;
begin
try
Test := TObservers.Create;
FConcreteObserver := ConcreteSubjec;
FConcreteObserver.AddObservers(Test);
finally
FreeAndNil(Test);
end;
end;
end.