Zitat von
Dani:
Wenn du eine neuen Nachkommen hinzufügst, muss die GetDeviceClass Methode aktualisiert werden, aber ich sehe auch keinen Weg, das zu vermeiden
Ich schon
Delphi-Quellcode:
uses
uDevice;
type
TBaseDings = class
private
fDevice: TDevice;
protected
class function MatchesDevice(const aDevice: TDevice): Boolean; virtual; abstract;
class procedure Register;
public
property Device: TDevice read fDevice;
class function CreateMatchingDings(const aDevice: TDevice): TBaseDings;
constructor Create(const aDevice: TDevice); virtual;
end;
TBaseDingsClass = class of TBaseDings;
implementation
uses
Contnrs;
var
ClassList : TClassList;
constructor TBaseDings.Create(const aDevice: TDevice);
begin
fDevice := aDevice;
end;
class function TBaseDings.CreateMatchingDings(const aDevice: TDevice): TBaseDings;
var
i : Integer;
BaseDingsClass : TBaseDingsClass;
begin
result := nil;
for i := 0 to ClassList.Count - 1 do
begin
BaseDingsClass := TBaseDingsClass(ClassList[i]);
if BaseDingsClass.MatchesDevice(aDevice) then
begin
result := BaseDingsClass.Create(aDevice);
Break;
end;
end;
end;
class procedure TBaseDings.Register;
begin
if ClassList.IndexOf(Self) = -1 then
ClassList.Add(Self);
end;
initialization
ClassList := TClassList.Create();
finalization
ClassList.Free();
end.
und nun für jedes nur noch Gerät sowas:
Delphi-Quellcode:
uses
uBaseDings,
uDevice;
type
TDings1Device = class(TDevice)
// mööp
end;
TDings1 = class(TBaseDings)
protected
class function MatchesDevice(const aDevice: TDevice): Boolean; override;
public
constructor Create(const aDevice: TDevice); override;
end;
implementation
{ TDings1 }
constructor TDings1.Create(const aDevice: TDevice);
begin
end;
class function TDings1.MatchesDevice(const aDevice: TDevice): Boolean;
begin
Result := aDevice is TDings1Device;
end;
initialization
// In die ClassList registrieren
TDings1.Register;
end.
Wobei ich in dem Schritt zwichen BaseDings und Dings1 noch die eigentliche Basisklasse setzen würde, die die grundlegende Funktionalität (virtuell) bereitstellt.