Difference between revisions of "How To Use Interfaces"
From Lazarus wiki
Jump to navigationJump to searchm |
m |
||
Line 1: | Line 1: | ||
Copy the text below and it will demonstrate how to use [[Interfaces]] to write less code, avoid code repetition,..., this is a fully working program. | Copy the text below and it will demonstrate how to use [[Interfaces]] to write less code, avoid code repetition,..., this is a fully working program. | ||
− | <syntaxhighlight>{$mode objfpc}{$H+} | + | <syntaxhighlight>program interfacesygenerics; |
+ | {$mode objfpc}{$H+} | ||
type | type | ||
ITestInterface = interface | ITestInterface = interface | ||
Line 13: | Line 14: | ||
end; | end; | ||
+ | TderivedObect = class(TBaseObject) | ||
+ | end; | ||
+ | |||
procedure TBaseObject.DoSomething; | procedure TBaseObject.DoSomething; | ||
begin | begin | ||
Line 26: | Line 30: | ||
begin | begin | ||
Writeln('Using regular interfaces'); | Writeln('Using regular interfaces'); | ||
− | I := | + | I := TderivedObect.Create as ITestInterface; |
if I <> nil then | if I <> nil then | ||
Writeln('Got interface OK. Calling it'); | Writeln('Got interface OK. Calling it'); | ||
I.DoSomething; | I.DoSomething; | ||
I.DoItAll; | I.DoItAll; | ||
− | end. | + | end.</syntaxhighlight> |
− | </syntaxhighlight> | ||
== See also == | == See also == | ||
Revision as of 17:24, 5 October 2021
Copy the text below and it will demonstrate how to use Interfaces to write less code, avoid code repetition,..., this is a fully working program.
program interfacesygenerics;
{$mode objfpc}{$H+}
type
ITestInterface = interface
['{3FB19775-F5FA-464C-B10C-D8137D742088}']
procedure DoSomething;
procedure DoItAll;
end;
TBaseObject = class(TInterfacedObject,ITestInterface)
procedure DoSomething;
procedure DoItAll;
end;
TderivedObect = class(TBaseObject)
end;
procedure TBaseObject.DoSomething;
begin
Writeln('TBaseObject DoSomething !');
end;
procedure TBaseObject.DoItAll;
begin
Writeln('TBaseObject DoItAll !');
end;
var
I: ITestInterface;
begin
Writeln('Using regular interfaces');
I := TderivedObect.Create as ITestInterface;
if I <> nil then
Writeln('Got interface OK. Calling it');
I.DoSomething;
I.DoItAll;
end.