Что в Delphi/Lazarus/FreePascal является лучшим способом унаследовать проверку родительского метода, которая выходит из метода? Допустим следующие классы и методы:
type
TPlant = class
public
FIsGreen: Boolean;
procedure DoPhotosynthesis; virtual;
end;
TChildPlant = class(TPlant)
public
procedure DoPhotosynthesis; override;
end;
Implementation
{TPlant}
procedure TPlant.DoPhotosynthesis;
begin
if not FIsGreen then Exit; //TPlants cannot do Photosynthesis if they are not green;
//basic photosynthesis implementation not to be included in child plants
end;
Следующая реализация полностью скроет унаследованную проверку и/или повторит код.
{TChildPlant}
procedure TChildPlant.DoPhotosynthesis;
begin
if not FIsGreen then Exit; //TPlant descendants cannot do Photosynthesis if they are not green;
//photosynthesis implementation...
end;
Является ли создание другого метода, скажем, DoSpecificPhotosynthesis
, и переопределение его лучшим способом реализации TChildPlant.DoPhotosynthesis
, который действительно проверяет not FIsGreen
и завершает работу, но не включает базовую реализацию фотосинтеза? (Смотрите ниже)
type
TPlant = class
public
IsGreen: Boolean;
procedure DoPhotosynthesis; virtual;
procedure DoSpecificPhotosynthesis: virtual;
end;
TChildPlant = class(TPlant)
public
procedure DoSpecificPhotosynthesis; override;
end;
Implementation
{TPlant}
procedure TPlant.DoPhotosynthesis;
begin
if not FIsGreen then Exit; //TPlants cannot do Photosynthesis if they are not green;
//photosynthesis implementation (child plants must implement their specific way);
DoSpecificPhotosynthesis;
end;
{TChildPlant}
procedure TChildPlant.DoSpecificPhotosynthesis;
begin
//photosynthesis implementation...
end;
Любые другие мысли?
protected
илиprivate
только для упрощения. Но вы правы. По моему мнению, мне вообще не нужно, чтобыDoPhotosynthesis
былоvirtual
. В любом случае, это никогда не будет переопределено. - person EMBarbosa   schedule 30.10.2013