Difference between revisions of "How To Use Interfaces"

From Free Pascal wiki
Jump to navigationJump to search
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+}{$interfaces com}
+
<syntaxhighlight>{$mode objfpc}{$H+}{$interfaces com} // which is the default
 
type
 
type
 
   ITestInterface = interface
 
   ITestInterface = interface

Revision as of 16:16, 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.

{$mode objfpc}{$H+}{$interfaces com} // which is the default
type
  ITestInterface = interface
    ['{3FB19775-F5FA-464C-B10C-D8137D742088}']
    procedure DoSomething;
    procedure DoItAll;
  end;

  TBaseObject = class(TInterfacedObject,ITestInterface)
    procedure DoSomething;
    procedure DoItAll;
  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 := TBaseObject.Create as ITestInterface;
  if I <> nil then
    Writeln('Got interface OK. Calling it');
  I.DoSomething;
  I.DoItAll;
end.

See also