您的位置:首页 > 编程语言 > Delphi

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

2014-09-29 11:08 483 查看
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一样.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐