Sign in Join
Wiki copytemporary

How To Use Interfaces: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: How To Use Interfaces

OldNewLine
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. 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.
2+
3+This example has two unrelated classes, but share the same COM interface. Since they are instantiated through that interface, destruction is automatic:
4+
5+``` pascal
6+program interfacesygenerics;
7+{$mode objfpc}{$H+}
8+type
9+ ITestInterface = interface
10+ ['{3FB19775-F5FA-464C-B10C-D8137D742088}']
11+ procedure DoSomething;
12+ procedure DoItAll;
13+ end;
14+
15+ TOneObject = class(TInterfacedObject,ITestInterface)
16+ procedure DoSomething;
17+ procedure DoItAll;
18+ end;
19+
20+ TOtherObject = class(TInterfacedObject,ITestInterface)
21+ procedure DoSomething;
22+ procedure DoItAll;
23+ end;
24+
25+ procedure TOneObject.DoSomething;
26+ begin
27+ Writeln('TOneObject DoSomething !');
28+ end;
29+
30+ procedure TOneObject.DoItAll;
31+ begin
32+ Writeln('TOneObject DoItAll !');
33+ end;
34+
35+ procedure TOtherObject.DoSomething;
36+ begin
37+ Writeln('TOtherObect DoSomething !');
38+ end;
39+
40+ procedure TOtherObject.DoItAll;
41+ begin
42+ Writeln('TOtherObect DoItAll !');
43+ end;
44+
45+var
46+ I: ITestInterface = nil;
47+begin
48+ Writeln('Using regular interfaces');
49+ I := TOneObject.Create as ITestInterface;
50+ if I <> nil then
51+ Writeln('Got interface OK. Calling it');
52+ I.DoSomething;
53+ I.DoItAll;
54+ I:=nil; // releases TOneObject
55+ I := TOtherObject.Create as ITestInterface;
56+ if I <> nil then
57+ Writeln('Got interface OK. Calling it');
58+ I.DoSomething;
59+ I.DoItAll;
60+end.
61+```
62+
63+## See also
64+
65+- [[Accessing the Interfaces directly]]
66+- [[Interfaces]]
67+- [[Understanding Interfaces]]
68+
69+---
70+*From the Free Pascal wiki, page "How To Use Interfaces", as it stood on 2021-10-06 after a change by Thaddy, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
71+Category: Example programs
72+Category: Interfaces
73+Category: Pascal

Back to history