Einzelnen Beitrag anzeigen

Robert_G
(Gast)

n/a Beiträge
 
#4

Re: Mehrere Klasseninstanzen in einem Array/einer TList

  Alt 3. Mai 2005, 16:08
Wenn du hier in der Sparte etwas herunterscrolls dürftest du das finden.
Les' dir das erstmal durch...


Da du es nicht gelesen hast... und shmia anscheinend auch nicht ...
Hier ein kleiner Bleisitift:

Simple SubClass mit einer Property...
Und einer exakt auf sie typisierten ObjectList.
Delphi-Quellcode:
unit uSubClass;

interface
uses
   Contnrs;

type
   TSubClass = class
   private
      fSomeProperty: Integer;
   protected
      procedure setSomeProperty(const aValue: Integer); virtual;
   public
      property SomeProperty: Integer read fSomeProperty write setSomeProperty;
   end;

{$DEFINE TYPED_OBJECT_LIST_TEMPLATE}
type
   _OBJECT_LIST_ITEM_ = TSubClass;
{$INCLUDE TypedObjectList_template.pas}
   TSubClassList = _OBJECT_LIST_;

implementation
{$INCLUDE TypedObjectList_template.pas}

{ TSubClass }

procedure TSubClass.setSomeProperty(const aValue: Integer);
begin
   fSomeProperty := aValue;
end;

end.
Und nun müssen wir nur noch die Liste benutzen.
Und zwar OHNE hässliche TypeCasts und vor allem OHNE untyped Pointer!
Delphi-Quellcode:
unit uMainClass;

interface
uses
   uSubClass;

type
   TMainClass = class
   private
      fSubClassList: TSubClassList;
   protected
      property SubClassList: TSubClassList read fSubClassList;
   public
      function CreateInstance(): Integer; virtual;
      function AccessInstance(const aIndex: Integer): TSubClass; virtual;

      constructor Create(); virtual;
      destructor Destroy();override;
   end;

implementation

{ TMainClass }

constructor TMainClass.Create();
begin
   //sollen die Instanzen mit der Liste freigegeben werden?
   // Ja -> True / Nein -> Rate mal ;-)
   fSubClassList := TSubClassList.Create(True);

end;

function TMainClass.CreateInstance(): Integer;
var
   NewInstance : TSubClass;
begin
   NewInstance := TSubClass.Create();
   NewInstance.SomeProperty := 1; // halt irgendwas in die Properties ;-)

   Result := SubClassList.Add(NewInstance);
end;

function TMainClass.AccessInstance(const aIndex: Integer): TSubClass;
begin
   if (aIndex >= 0) and (aIndex < SubClassList.Count) then
      Result := SubClassList[aIndex]
   else
      raise SomeJanzBöserIndexException.Create(aIndex, 0, SubClassList.Count);
end;


destructor TMainClass.Destroy();
begin
   fSubClassList.Free();
   inherited;
end;

end.
  Mit Zitat antworten Zitat