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

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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值