Usando Generics com Delphi >= 2009

255 views
Skip to first unread message

Ricardo Gavira

unread,
Jul 19, 2011, 5:19:05 PM7/19/11
to DUG-RS - Delphi Users Group Rio Grande do Sul
Olá pessoal.

Vou postar aqui um exemplo que fiz utilizando Generics do Delphi,
muito útil para diminuir o acoplamento dos objetos e proporciona uma
redução considerável de código.
É um exemplo bem simples, só para conhecermos essa estrutura dos novos
delphis.


Para fazer a conversão dos tipos sem usar Rtti, criei uma interface e
uma classe generica.

unit uConverter;

interface

type
IConverter = Interface(IInterface)
function GenericAsString(const Value): string;
function GenericAsInteger(const Value): Integer;
function GenericAsDouble(const Value): Double;
function GenericAsObject(const Value): TObject;
function GenericAsInterface(const Value): IInterface;
function GenericAsPointer(const Value): Pointer;
end;

TConverter<T> = class(TInterfacedObject, IConverter)
public
function GenericAsDouble(const Value): Double;
function GenericAsInteger(const Value): Integer;
function GenericAsInterface(const Value): IInterface;
function GenericAsPointer(const Value): Pointer;
function GenericAsString(const Value): string;
function GenericAsObject(const Value): TObject;
end;

implementation

{ TConverter<T> }

function TConverter<T>.GenericAsDouble(const Value): Double;
begin
Result := Double(Value);
end;

function TConverter<T>.GenericAsInteger(const Value): Integer;
begin
Result := Integer(Value);
end;

function TConverter<T>.GenericAsInterface(const Value): IInterface;
begin
Result := IInterface(Value);
end;

function TConverter<T>.GenericAsObject(const Value): TObject;
begin
Result := TObject(Value);
end;

function TConverter<T>.GenericAsPointer(const Value): Pointer;
begin
Result := Pointer(Value);
end;

function TConverter<T>.GenericAsString(const Value): string;
begin
Result := String(Value);
end;

end.



Agora vamos criar nossa classe generica:


unit Unit2;

interface

uses StdCtrls, TypInfo, SysUtils;

type
TGenerics<T> = class
private
FValue: T;
public
function getValue: T;
procedure setValue(const Value: T);
procedure show(memo: TMemo);
end;

implementation

uses uConverter, Rtti;

{ TGenerics<T> }

function TGenerics<T>.getValue: T;
begin
result := self.FValue;
end;

procedure TGenerics<T>.setValue(const Value: T);
begin
self.FValue := Value;
end;

procedure TGenerics<T>.show(memo: TMemo);
var
Conv: TConverter<T>;
texto: string;
begin
Conv := TConverter<T>.Create;
if (UpperCase(GetTypeName(TypeInfo(T))) = 'STRING') then
texto := Conv.GenericAsString(self.FValue)
else if (UpperCase(GetTypeName(TypeInfo(T))) = 'INTEGER') then
texto := IntToStr(Conv.GenericAsInteger(self.FValue));

memo.Lines.Add(texto);
end;

end.



Agora para chamar você deve criar um novo form, colocar um botão e
utilizar o código abaixo.

procedure TForm1.Button1Click(Sender: TObject);
var
g1: TGenerics<string>;
g2: TGenerics<integer>;
begin
g1 := TGenerics<string>.Create;
g1.setValue('Hello World');
g1.show(memo1);

g2 := TGenerics<integer>.Create;
g2.setValue(123);
g2.show(memo1);
end;


Então, utilizando da mesma classe conseguimos tratar 2 tipos, no nosso
caso string e integer, mais poderia ser Pessoa, Funcionario, Venda,
Pedido, etc.

Espero ter colaborado com todos no sentido de incentivar a pesquisa, o
estudo das novas tecnologias que vem para facilitar a nossa vida no
dia dia, proporcionando também bem menos tempo de codificação e também
de retrabalho.


abraços

Newton Michel De Oliveira

unread,
Jul 19, 2011, 5:51:34 PM7/19/11
to dug...@googlegroups.com, DUG-RS - Delphi Users Group Rio Grande do Sul
Ricardo,
Muito boa sua iniciativa. Com iniciativas assim vamos tornar nosso grupo cada vez mais forte a ativo... Agora vamos testar o código e claro, de alguém tiver idéias ou novas funcionalidades contribua...


Enviado via iPhone

> --
> Você recebeu esta mensagem porque está inscrito no "DUG-RS -
> Delphi Users Group Rio Grande do Sul" em Grupos do Google.
> Acesse o nosso BLOG em http://www.dug-rs.org e contribua com a comunidade Delphi do Rio Grande do Sul
> Para postar neste grupo, envie um e-mail para dug...@googlegroups.com
> Para cancelar a sua inscrição neste grupo, envie um e-mail para
> dug-rs-un...@googlegroups.com
> Para ver mais opções, visite este grupo em
> http://groups.google.com.br/group/dug-rs?hl=pt-BR
> Twitter: @dugrs

Reply all
Reply to author
Forward
0 new messages