Skip to content

Instantly share code, notes, and snippets.

@freeonterminate
Last active December 31, 2015 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freeonterminate/7912166 to your computer and use it in GitHub Desktop.
Save freeonterminate/7912166 to your computer and use it in GitHub Desktop.
Interface のサンプル
program Project1;
uses
System.SysUtils;
type
// Sample Interface
IFoo = interface
['{174C7089-888D-4B3A-A348-DBAEC0AA70A5}']
function GetBar: String;
property Bar: String read GetBar;
end;
// IFoo を実装するクラス
TFooImpl = class(TAggregatedObject, IFoo)
private
function GetBar: String;
end;
// TFooImpl に IFoo の実装を委任してるクラス
TBaz = class(TInterfacedObject, IFoo)
private
FFoo: IFoo;
public
constructor Create; reintroduce;
property FooIntf: IFoo read FFoo implements IFoo;
end;
{ TFooImple }
function TFooImpl.GetBar: String;
begin
Result := 'Bar';
end;
{ TBaz }
constructor TBaz.Create;
begin
inherited;
FFoo := TFooImpl.Create(Self);
end;
{ Main }
var
Foo: IFoo;
GUID: TGUID;
begin
// Inteface に代入, TBaz 自体は IFoo を実装していないのに代入できる
Foo := TBaz.Create;
Writeln(Foo.Bar);
// Inteface を GUID に代入
GUID := IFoo;
Writeln(GUIDToString(GUID));
// Inteface から元の型を調べてみる
Writeln((Foo as TObject).ClassName); // Implements からでも元の型が取れる
Readln;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment