unit MBSubject;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, MBObserver;
type
IMBSubject =
interface
['
{A89B6DD9-711C-4444-BF29-1AB0335A489C}']
procedure AddObserver(Observer: IMBObserver);
procedure RemoveObserver(Observer: IMBObserver);
procedure ClearObservers;
procedure NotifiyObservers;
end;
{ TMBSubject }
TMBSubject =
class(TComponent, IMBSubject)
private
FEnabled: Boolean;
FObservers: TInterfaceList;
public
constructor Create(AOwner: TComponent);
override;
destructor Destroy;
override;
procedure AddObserver(Observer: IMBObserver);
procedure RemoveObserver(Observer: IMBObserver);
procedure ClearObservers;
procedure NotifiyObservers;
published
property Enabled: Boolean
read FEnabled
write FEnabled
default True;
end;
procedure Register;
implementation
procedure Register;
begin
{$I mbsubject_icon.lrs}
RegisterComponents('
MBComponents',[TMBSubject]);
end;
{ TMBSubject }
constructor TMBSubject.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FObservers:=TInterfaceList.Create;
FEnabled:=True;
end;
destructor TMBSubject.Destroy;
begin
if Assigned(FObservers)
then FreeAndNil(FObservers);
inherited Destroy;
end;
procedure TMBSubject.AddObserver(Observer: IMBObserver);
begin
if FObservers.IndexOf(Observer) = -1
then FObservers.Add(Observer);
end;
procedure TMBSubject.RemoveObserver(Observer: IMBObserver);
begin
FObservers.Remove(Observer);
end;
procedure TMBSubject.ClearObservers;
begin
FObservers.Clear;
end;
procedure TMBSubject.NotifiyObservers;
var
i: Integer;
Observer: IMBObserver;
begin
if not FEnabled
then Exit;
for i := 0
to Pred(FObservers.Count)
do
if Supports(FObservers.Items[i], IMBObserver, Observer)
then Observer.SubjectChanged(Self);
end;
end.