Delphi 灵活运用接口(interface), 隐藏核心代码, 设计低耦合程序.

来源:互联网 发布:电视网络接口怎么安装 编辑:程序博客网 时间:2024/05/16 00:06
2007年04月18日 星期三 08:34

原创作品, 如有转载请注明出处.
COPYRIGHT BY cnCharles, ALL RIGHTS RESERVED.
delphi群: 16497064, blog: http://hi.baidu.com/cnCharles

程序详细代码如下

program InterfaceTest;

uses
     Forms,
     Main in 'Main.pas' {frmMain},
     Test in 'Test.pas' {frmTest},
     PubIntfs in 'PubIntfs.pas';

{$R *.res}

begin
     Application.Initialize;
     Application.CreateForm(TfrmMain, frmMain);
     Application.Run;
end.

//-----------------------------------------------------------------------------------------------

unit Main;
{
Date         : 2007-04-18
Author       : cnCharles
Description: 应用程序主界面单元
}
interface

uses
     Forms, Dialogs, StdCtrls, Classes, Controls, PubIntfs;

type
     TfrmMain = class(TForm, IMainFormTest)
       Button1: TButton;
       procedure Button1Click(Sender: TObject);
     private
       { Private declarations }
     protected
       procedure SayHello;
     public
       { Public declarations }
     end;

var
     frmMain: TfrmMain;

implementation

uses Test;

{$R *.dfm}

procedure TfrmMain.Button1Click(Sender: TObject);
begin
     with TfrmTest.Create(Self) do
       Show;
end;

procedure TfrmMain.SayHello;
begin
     ShowMessage('I''m a MainForm');
end;

end.

//--------------------------------------------------------------------------------------------------

unit Test;
{
Date         : 2007-04-18
Author       : cnCharles
Description: 接口测试
}
interface

uses
     Forms, StdCtrls, Classes, Controls;

type
     TfrmTest = class(TForm)
       Button1: TButton;
       procedure Button1Click(Sender: TObject);
     private
       { Private declarations }
     public
       { Public declarations }
     end;

var
     frmTest: TfrmTest;

implementation

uses PubIntfs;

{$R *.dfm}

procedure TfrmTest.Button1Click(Sender: TObject);
begin
     (Application.MainForm as IMainFormTest).SayHello;
end;

end.

//-------------------------------------------------------------------------------------------------

unit PubIntfs;
{
Date         : 2007-04-18
Author       : cnCharles
Description: 对外公开接口
}
interface

const
     IID_MainFormTest = '{6E6F8E9C-E147-47DF-95F8-A5861DD8F393}';
type
     IMainFormTest = interface
       [IID_MainFormTest]
       procedure SayHello;
     end;

implementation

end.

不 知道你们有没有看明白, 在Test单元中并没有uses(引用) Main单元, 但是但是确可以调用它的 SayHello方法. 在这个Demo中还要明白一个要点, Application.CreateForm 第一次创建派生自TForm 的Form即为程序的主窗体.     Application是一个全局变量, 定义在Forms单元中, 只要引用了Forms单元就可以引用Application,     Screen对象也与Application一样.

0 0
原创粉丝点击