[fpc-pascal] Implementing Factory Method with Pascal

luciano de souza luchyanus at gmail.com
Fri Nov 27 22:21:37 CET 2015


Hello all,

I'd like to understand how to implement the Factory Method pattern in Pascal.

In my example, there are four classes:
1. TAnimal - The parent and abstract class;
2. TDog and TCat - The specialized classes;
3. TAnimalFactory - The class which creates instances of animals,
having received a enumerator as a parameter.

The method "live" is common to TAnimal, Tdog and TCat. However, "bark"
is found only in TDog.

In the following code, the compiler says that animal does not
possesses "bark" as a method. It's right. The behaviour is implemented
only in the derived class.

But, if this not works, how to implement the Factory Method in Freepascal?

		program test;
{$mode objfpc}{$H+}

uses
tsbase;

var
animal: TAnimal;
BEGIN
animal := TAnimalFactory.create(atDog);
try
animal.bark; // Here is the error. If the call were "animal.live, no
errors would be shown. The code does not fails with (animal as
TDog).bark, but it does not make sense. The factory should allow to
create the instance only with the enumerator, without casting.

finally
animal.free;
end;
END.
		
		unit tsbase;
{$mode objfpc}{$H+}

interface
type
TAnimal = class(TObject)
public
procedure live; virtual; abstract;
end;

TDog = class(TAnimal)
public
procedure live; override;
procedure bark;
end;

TCat = class(TAnimal)
public
procedure live; override;
end;

TAnimalType = (atDog, atCat);

TAnimalFactory = class(TObject)
public
class function create(AType: TAnimalType):TAnimal;
end;

implementation
{TDog}
procedure TDog.live;
begin
writeln('Um cachorro vive');
end;

procedure TDog.bark;
begin
writeln('Um cachorro foge');
end;

{TCat}
procedure TCat.live;
begin
writeln('Um gato vive');
end;

{TAnimalFactory}
class function TAnimalFactory.create(AType: TAnimalType):TAnimal;
begin
case AType of
atDog: result := TDog.create;
atCat: result := TCat.create;
end;
end;

end.

Well, I am studying design patterns, but I really does not understand
how to solve this problem.

I thank you for any tip.

Best regards,

-- 
Luciano de Souza



More information about the fpc-pascal mailing list