|
代码: 现在把全文的代码列举如下,其中有一些上面没有给出的代码,但它们也很重要,列在一起方便大家浏览,请仔细查看下面的代码以获得需要的信息,当然本文也仅仅是做为一个简单的例子,举出了一些常见的问题和解决技巧,以及象这样的接口编程的一个可能应用。 接口: IFoo = interface; IFooManager = interface ['{3A10DC39-4B14-4C61-B657-E445C55408B6}'] function CreateAFoo:IFoo; procedure DelAFoo(id:integer); function GetFooNum:integer; function GetFooByID(id:integer):IFoo; end; IFoo = interface //我们要维护的对象,只实现了一个简单的加法运算做为例子 ['{22C541AA-0BA4-4092-B0EB-D267AB1FF001}'] function fooAdd(x,y:integer):integer; end; TFoo的声明和实现: TFoo = class(TMyInterfacedObject,IFoo) protected function fooAdd(x,y:integer):integer; end; implementation { TFoo } function TFoo.fooAdd(x, y: integer):integer; begin result:=x+y; end; 工厂类的声明和实现: TFooManager=class(TMyInterfacedObject,IFooManager) private FList:array of TFoo; FooNum:integer; protected constructor Create; function CreateAFoo:IFoo; procedure DelAFoo(id:integer); function GetFooNum:integer; function GetFooByID(id:integer):IFoo; public destructor Destroy;override; end; var FooMan:TFooManager; implementation { TFooManager } constructor TFooManager.Create; begin FooNum:=0; end; function TFooManager.CreateAFoo: IFoo; begin inc(FooNum); if length(FList)<FooNum then setlength(FList,FooNum*2); FList[FooNum-1]:=TFoo.Create; result:=FList[FooNum-1] as IFoo; end; procedure TFooManager.DelAFoo(id:integer); var i:integer; begin if FooNum>0 then begin FList[id].Free; for i:=id to FooNum-2 do begin FList[i]:=FList[i+1]; end; FList[FooNum-1]:=nil; Dec(FooNum); end; end; destructor TFooManager.Destroy; //在释放工厂类前释放所有所维护的对象 var i:integer; begin for i:=0 to FooNum-1 do begin FList[i].Free; FList[i]:=nil; end; Finalize(Flist); inherited; end; function TFooManager.GetFooByID(id: integer): IFoo; begin result:=FList[id] as IFoo; end; function TFooManager.GetFooNum: integer; begin result:=FooNum; end; Dll中仅有的两个导出函数: function GetFooManIntf:IFooManager;stdcall; begin if not assigned(FooMan) then begin FooMan:=TFooManager.Create; end; result:=FooMan as IFooManager; end; procedure FreeLib;stdcall; //释放工厂类 begin if assigned(FooMan) then begin FooMan.Free; FooMan:=nil; end; end;
|