接口的另一种用法
这个修改上个文章《接口实现多重继承》的例子。
1 unit Ucat; 2 3 interface 4 uses System.SysUtils,Windows,Messages,System.Classes,Vcl.Graphics,Vcl.Controls,Vcl.Forms; 5 6 type 7 IAction = interface(IInterface) 8 function say: string; 9 end; 10 11 ICat = interface(IAction) 12 end; 13 14 IDoraemon = interface(IAction) 15 end; 16 17 TProperty= class(TInterfacedObject,Icat) 18 private 19 Fname: string; 20 FColor: string; 21 public 22 constructor create; 23 property name:string read Fname write Fname; 24 property Color: string read FColor write FColor; 25 function say:string; 26 end; 27 28 TDoraemon = Class(TInterfacedObject,IDoraemon) 29 private 30 function say: string; 31 End; 32 33 TPersianCat= class(Tproperty) 34 35 public 36 constructor create; 37 end; 38 39 TBlueCat= class(TProperty) 40 public 41 constructor create; 42 end; 43 44 TSiamCat= class(TProperty) 45 46 public 47 constructor create; 48 end; 49 50 51 52 53 54 implementation 55 56 { TProperty } 57 58 constructor TProperty.create; 59 begin 60 Fname := '猫'; 61 end; 62 63 function TProperty.say: string; 64 begin 65 result:= '喵'; 66 end; 67 68 { TDoraemon } 69 70 function TDoraemon.say: string; 71 begin 72 result:= '我是哆啦a梦'; 73 end; 74 75 { TAdmix } 76 77 78 { TPersianCat } 79 80 constructor TPersianCat.create; 81 begin 82 Fname:='波斯猫'; 83 FColor:= '白色'; 84 end; 85 86 { TBlueCat } 87 88 constructor TBlueCat.create; 89 begin 90 Fname:= '俄罗斯蓝猫'; 91 FColor:= '蓝色'; 92 end; 93 94 { TSiamCat } 95 96 constructor TSiamCat.create; 97 begin 98 Fname:= '暹罗猫'; 99 FColor:= '咖啡色'; 100 end; 101 102 end.
1 unit Uadmin; 2 3 interface 4 5 uses 6 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, 7 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Ucat; 8 9 type 10 TForm1 = class(TForm) 11 Button1: TButton; 12 Label1: TLabel; 13 Button2: TButton; 14 Button3: TButton; 15 Button4: TButton; 16 procedure Button1Click(Sender: TObject); 17 procedure Button2Click(Sender: TObject); 18 procedure Button3Click(Sender: TObject); 19 procedure Button4Click(Sender: TObject); 20 private 21 { Private declarations } 22 public 23 procedure say(cat: TProperty); overload; 24 procedure say(cat: IDoraemon); overload; 25 { Public declarations } 26 end; 27 28 29 var 30 Form1: TForm1; 31 32 implementation 33 34 35 {$R *.dfm} 36 procedure TForm1.say(cat: TProperty); 37 begin 38 label1.caption:=cat.Color+' '+ cat.name+' '+cat.say; 39 end; 40 41 procedure TForm1.say(cat: IDoraemon); 42 begin 43 label1.Caption:= cat.say; 44 end; 45 46 procedure TForm1.Button1Click(Sender: TObject); 47 begin 48 say(TPersianCat.create); 49 end; 50 51 procedure TForm1.Button2Click(Sender: TObject); 52 begin 53 say(TBlueCat.create); 54 end; 55 56 procedure TForm1.Button3Click(Sender: TObject); 57 begin 58 say(TSiamCat.create); 59 end; 60 61 procedure TForm1.Button4Click(Sender: TObject); 62 begin 63 say(TDoraemon.Create); 64 end; 65 66 end.

浙公网安备 33010602011771号