首页 / 软件开发 / Delphi / 第十九章-Delphi自定义部件开发(四)(3)
第十九章-Delphi自定义部件开发(四)(3)2007-05-073. 公布Pen和Brush在缺省情况下,一个Canvas具有一个细的、黑笔和实心的白刷,为了使用户在使用Shape控制时能改变Canvas的这些性质,必须能在设计时提供这些对象;然后在画时使用这些对象,这样附属的Pen或Brush被称为Owned对象。管理Owned对象需要下列三步:● 声明对象域● 声明访问属性● 初始化Owned对象⑴ 声明Owned对象域拥有的每一个对象必须有对象域的声明,该域在部件存在时总指向Owned对象。通常,部件在constructor中创建它,在destructor中撤消它。Owned对象的域总是定义为私有的,如果要使用户或其它部件访问该域,通常要提供访问属性。下面的代码声明了Pen和Brush的对象域:typeTSampleShape=class(TGraphicControl)privateFPen: TPen;FBrush: TBrush;end;⑵ 声明访问属性可以通过声明与Owned对象相同类型的属性来提供对Owned对象的访问能力。这给使用部件的开发者提供在设计时或运行时访问对象的途径。下面给Shape控制提供了访问Pen和Brush的方法typeTSampleShape=class(TGraphicControl)privateprocedure SetBrush(Value: TBrush);procedure SetPen(Value: TPen);publishedproperty Brush: TBrush read FBrush write SetBrush;property Pen: TPen read FPen write SetPen;end;然后在库单元的implementation部分写SetBrush和SetPen方法:procedure TSampleShape.SetBrush(Value: TBrush);beginFBrush.Assign(Value);end;procedure TSampleShape.SetPen(Value: TPen);beginFPen.Assign(Value);end;⑶ 初始化Owned对象部件中增加了的新对象,必须在部件constructor中建立,这样用户才能在运行时与对象交互。相应地,部件的destructor必须在撤消自身之前撤消Owned对象。因为Shape控制中加入了Pen和Brush对象,因此,要在constructor中初始化它们,在destructor中撤消它们。① 在Shape控制的constructor中创建Pen和Brushconstructor TSampleShape.Create(Aowner: TComponent);begininherited Create(AOwner);Width := 65;Height := 65;FPen := TPen.Create;FBrush := TBrush.Create;end;② 在部件对象的声明中覆盖destructortypeTSampleShape=class(TGraphicControl)publicconstrustor.Create(Aowner: TComponent); override;destructor.destroy; override;end;③ 在库单元中的实现部分编写新的destructordestructor TSampleShape.destroy;beginFPen.Free;FBrush.Free;inherited destroy;end;