關於觀察者模式.請大家指點(0分)

  • 主题发起人 主题发起人 snow_white
  • 开始时间 开始时间
S

snow_white

Unregistered / Unconfirmed
GUEST, unregistred user!
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
//=======================================subject class
type
TSubJect=Class(TComponent)
private
FList:TStringList;
protected
procedure Add(xKey:String;xObj:TObject);virtual;
procedure del(xObj:TObject);virtual;
public
procedure NotifyObserver();virtual;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
end;
//===================================observer
type
TObserver = class
private
protected
procedure add();
public
Procedure update(xstr:string);
end;

type
TfrmObject = class(TForm)
edSubject: TEdit;
memObserver: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edSubjectChange(Sender: TObject);
private
FObserver :TObserver ;
FSubJect :TSubJect ;
protected
public
{ Public declarations }
end;

var
frmObject: TfrmObject;
implementation
{$R *.DFM}
constructor TSubJect.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FList := TStringlist.Create;
end;

destructor TSubJect.Destroy;
begin
FList.Free;
inherited Destroy;
end;
procedure TSubJect.Add(xKey:String;xObj:TObject);
begin
FList.AddObject(xKey,xObj);
end;

procedure TSubJect.del(xObj:TObject);
begin
if xobj=nil then
exit;
FList.Delete(FList.IndexofObject(xObj)) ;
end;

procedure TSubJect.NotifyObserver();
var
i:Integer;
begin
For i:=0 to FList.Count-1do
begin
TObserver(FList.Objects).Update('Y');
end;
end;

Procedure TObServer.update(xstr:string);
begin
if xStr='Y' then
add();
end;
procedure TObserver.add();
begin
frmObject.memObserver.Lines.Add( frmObject.edSubject.Text)
end;

procedure TfrmObject.FormCreate(Sender: TObject);
begin
FSubJect:=TSubJect.Create(nil) ;
FObserver:=TObserver.Create ;
FSubJect.Add('FObServer',FObserver);
end;

procedure TfrmObject.FormDestroy(Sender: TObject);
begin
FSubJect.del(FObserver);
FsubJect.Free;
FObserver.Free;
end;

procedure TfrmObject.edSubjectChange(Sender: TObject);
begin
FSubJect.NotifyObserver;
end;

end.
 
把Observer定义为接口,TfrmObject = class(TForm) 实现 这个接口,这样会更好,针对抽象。或者TObserver定义为抽象类。
 

Similar threads

后退
顶部