Einzelnen Beitrag anzeigen

Blup

Registriert seit: 7. Aug 2008
Ort: Brandenburg
1.429 Beiträge
 
Delphi 10.4 Sydney
 
#21

Re: kleines OOP Beispiel bitte um Anmerk./Verbesserungvorsch

  Alt 17. Okt 2008, 10:52
Man sollte zwischen Eingabefehlern und fachlichen Fehlern unterscheiden.
Ein leeres Eingabefeld sollte im Formular erkannt werden, ein Eingabe der Zahl 0 für einen Divisor aber in der fachlichen Logik.

Die fachliche Logik sollte besser nicht in der Formular-unit implementiert werden (Wiederverwendbarkeit).
Ein OOP-Beispiel ohne Vererbung ist ziemlich sinnfrei, deshalb hier mein Vorschlag:
Delphi-Quellcode:
unit OOP_Calc;

interface

uses
  Classes;

type
  TCustomOperation = class(TObject)
  private
    FWert1: Double;
    FWert2: Double;
    FErgebnis: Double;
    FBerechnet: Boolean;
    function GetErgebniss: Double;
    procedure SetWert(var AWert: Double; AValue: Double);
  protected
    procedure SetWert1(AValue: Double); virtual;
    procedure SetWert2(AValue: Double); virtual;
    function Calc: Double; virtual; abstract;
  public
    property Wert1: Double read FWert1 write SetWert1;
    property Wert2: Double read FWert2 write SetWert2;
    property Ergebnis: Double read GetErgebniss;
  end;

  TSumme = class(TCustomOperation)
  protected
    function Calc: Double; override;
  end;

  TDifferenz = class(TCustomOperation)
  protected
    function Calc: Double; override;
  end;

  TProdukt = class(TCustomOperation)
  protected
    function Calc: Double; override;
  end;

  TQuotient = class(TCustomOperation)
  private
    procedure CheckDivisor(AValue: Integer);
  protected
    procedure SetWert2(AValue: Double); override;
    function Calc: Double; override;
  end;

implementation

const
  ERROR_DIVISORNULL = 'Der Divisor darf nicht Null sein.'

function TCustomOperation.GetErgebniss: Double;
begin
  if not FBerechnet then
  begin
    FErgebnis := Calc;
    FBerechnet := True;
  end;
  Result := FErgebnis;
end;

procedure TCustomOperation.SetWert(var AWert: Double; AValue: Double);
begin
  if AWert <> AValue then
  begin
    AWert := AValue;
    FBerechnet := False;
  end;
end;

procedure TCustomOperation.SetWert1(AValue: Double);
begin
  SetWert(FWert1, AValue);
end;

procedure TCustomOperation.SetWert2(AValue: Double);
begin
  SetWert(FWert2, AValue);
end;

function TSumme.Calc: Double;
begin
  Result := FWert1 + FWert2;
end;

function TDifferenz.Calc: Double;
begin
  Result := FWert1 - FWert2;
end;

function TProdukt.Calc: Double;
begin
  Result := FWert1 * FWert2;
end;

procedure TQuotient.CheckDivisor(AValue: Integer);
begin
  if AValue = 0 then
    raise Exception.Create(ERROR_DIVISORNULL);
end;

function TQuotient.Calc: Double;
begin
  CheckDivisor(FWert2);
  Result := FWert1 / FWert2;
end;

procedure TQuotient.SetWert2(AValue: Double);
begin
  CheckDivisor(AValue);
  inherited SetWert(FWert2, AValue);
end;
  Mit Zitat antworten Zitat