Difference between revisions of "How To Use Interfaces"

From Lazarus wiki
Jump to navigationJump to search
m
Line 16: Line 16:
 
   end;
 
   end;
  
   TderivedObect = class(TBaseObject)
+
   TderivedObect = class(TBaseObject,ITestInterface)
 +
    procedure DoSomething;
 +
    procedure DoItAll;
 
   end;
 
   end;
 
    
 
    
Line 28: Line 30:
 
     Writeln('TBaseObject DoItAll !');
 
     Writeln('TBaseObject DoItAll !');
 
   end;
 
   end;
 +
  procedure TderivedObect.DoSomething;
 +
  begin
 +
    Writeln('TderivedObect DoSomething !');
 +
  end;
 +
 +
  procedure TderivedObect.DoItAll;
 +
  begin
 +
    Writeln('TderivedObect DoItAll !');
 +
  end;
 +
 
 
var
 
var
 
   I: ITestInterface;
 
   I: ITestInterface;

Revision as of 16:35, 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. The default interface in FPC is COM, which makes that once a class with an interface is instantiated as that interface it will automatically be released. Note if you change the interface type to CORBA it WILL leak.

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,ITestInterface)
    procedure DoSomething;
    procedure DoItAll;
  end;
  
  procedure TBaseObject.DoSomething;
  begin
    Writeln('TBaseObject DoSomething !');
  end;

  procedure TBaseObject.DoItAll;
  begin
    Writeln('TBaseObject DoItAll !');
  end;
  procedure TderivedObect.DoSomething;
  begin
    Writeln('TderivedObect DoSomething !');
  end;

  procedure TderivedObect.DoItAll;
  begin
    Writeln('TderivedObect 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.

See also