Thema: Delphi Objekt Casting

Einzelnen Beitrag anzeigen

Blup

Registriert seit: 7. Aug 2008
Ort: Brandenburg
1.477 Beiträge
 
Delphi 12 Athens
 
#7

AW: Objekt Casting

  Alt 2. Feb 2012, 10:23
Ein Konzept:
Delphi-Quellcode:
unit UnitFramework;

type
  TWirter = class()
    function Accept(AObject: TObject): Boolean; virtual; abstract;
    procedure Write(AObject); virtual; abstract;
  end;

  TReader = class()
    function Accept(AObject: TObject): Boolean; virtual; abstract;
    procedure Read(AObject); virtual; abstract;
  end;

  TFrameWork = class()
  private
    FWriterList: TObjectList;
    FReaderList: TObjectList;
  public
    procedure RegisterWriter(AWriter: TWriter);
    procedure RegisterReader(AReader: TReader);
    procedure Read(AObject: TObject);
    procedure Write(AObject: TObject);
  end;

var
  MyFrameWork: TFrameWork;

implementation

procedure TFrameWork.RegisterWriter(AWriter: TWriter);
begin
  FWriterList.Add(AWriter);
end;

procedure TFrameWork.RegisterReader(AReader: TReader);
begin
  FReaderList.Add(AReader);
end;

procedure TFrameWork.Read(AObject: TObject);
begin
  for Reader in FReadList do
    if Reader.Accept(AObject) then
    begin
      Reader.Read(AObect);
      Exit;
    end;
end;

procedure TFrameWork.Write(AObject: TObject);
begin
  for Writer in FWriterList do
    if Writer.Accept(AObject) then
    begin
      Writer.Write(AObect);
      Exit;
    end;
end;
Delphi-Quellcode:
unit UnitMyObject;

type
  TMyObject = class()
  end;
Delphi-Quellcode:
unit UnitMyObjectReadWrite;

uses
  UnitFramework, UnitMyObject;

type
  TReader_MyObject = class(TReader)
    function Accept(AObject: TObject): Boolean; override;
    procedure Read(AObject); override;
  end;

implementation

function TReader_MyObject.Accept(AObject: TObject): Boolean;
begin
  Result := AObject is TMyObject;
end;

procedure TReader_MyObject.Read(AObject);
begin
  with AObject as TMyObject do
  begin
    {...}
  end;
end;

initialization
  MyFrameWork.RegisterReader(TReader_MyObject.Create);

end.
  Mit Zitat antworten Zitat