Last active
December 31, 2015 01:09
-
-
Save freeonterminate/7912166 to your computer and use it in GitHub Desktop.
Interface のサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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