委托实现是Delphi提供接口技术后引入的功能,是指用另一个类或接口实现某个接口的方法在定义
一个类时,如果该类(如TDraw)实现一个接口(如:IDraw),那么该类必须实现接口中的所以方法。通过
委托实现,TDraw类就不必实现IDraw接口中的所以方法,可以通过在TDraw类中定义一个实现IDraw接口的类
的一个属性,也可以通过在TDraw类中定义一个IDraw接口或其派生接口类型的属性,来委托实现IDraw接口的所
以方法。在定义属性时,需要使用implements关键字,让编译器在该属性中搜索实现IDraw接口的方法。
unit Unit4;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls,printers, jpeg;
type
=============================================================================================
IDraw = interface
['{20816C73-6BBE-4AB8-9857-5148DBBD14CD}']
procedure DrawForm;
end;
IDrawText = interface(IDraw)
procedure DrawText;
end;
TDraw = Class(TInterfacedObject,IDraw)
private
FDraw:IDrawText;
published
property Draw:IDrawText Read FDraw implements IDraw;
public
Constructor Create;virtual;
end;
TDrawText = Class(TInterfacedObject,IDrawText)
public
procedure DrawForm;
procedure DrawText;
constructor Create;virtual;
end;
=============================================================================================
TForm4 = class(TForm)
img1: TImage;
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form4: TForm4;
DrawText1:IDrawText;
DrawInterface:IDraw;
Draw:TDraw;
implementation
{$R *.dfm}
{ TDraw }
constructor TDraw.Create;
begin
Inherited;
end;
{ TDrawText }
constructor TDrawText.Create;
begin
Inherited;
end;
procedure TDrawText.DrawForm;
begin
Form4.Brush.Bitmap := Form4.img1.Picture.Bitmap;
Form4.Repaint;
end;
procedure TDrawText.DrawText;
begin
Form4.Canvas.TextOut(10,5,'熊惠花');
end;
procedure TForm4.btn1Click(Sender: TObject);
begin
Draw := TDraw.Create;
DrawText1 := TDrawText.Create;
Draw.FDraw := DrawText1;
DrawInterface := Draw;
DrawInterface.DrawForm;
DrawText1.DrawText;
end;
end.