简单设计模式的应用.

                            首先声明,我没有学过设计模式,不过知道下面的技巧是设计模式的一种.

//==============================================================================
// Unit Name: CommonUnit
// Author   : ysai
// Date     : 2003-01-09
// Purpose  :
// History  :
//==============================================================================

unit CommonUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes,Forms,StrUtils;

resourcestring
//==============================================================================
//提示
//==============================================================================
  SInformation      = '信息';
  SError            = '错误';
  SWarning          = '警告';
  SConfirm          = '确认';

type
  //全局对象
  TGlobalObject = class(TComponent)
  private
    FApplicationPath  : String;         //应用程序路径
    FInsertItemPath   : String;         //插件路径
    FGridIniFileName  : String;         //表格INI文件
    FLastErrorMessage : String;         //最后的错误信息
  public
    constructor Create(AOwner: TComponent);reintroduce;override;
    property ApplicationPath  : String  read  FApplicationPath;
    property GridIniFileName  : String  read  FGridIniFileName;
    property LastErrorMessage : String  read  FLastErrorMessage write FLastErrorMessage;
    property InsertItemPath   : String  read  FInsertItemPath;
    //例子,一个函数
    function MsgBox(
        const AMsg    : Variant;
        const ATitle  : string='';
        const AFlag   : longint=0;
        const AHandle : HWND=0
        ):integer;
  published
  end;

var
  GlobalObject  : TGlobalObject;

implementation

{ TGlobalObject }

constructor TGlobalObject.Create(AOwner: TComponent);
begin
  FApplicationPath  :=  ExtractFilePath(Application.ExeName);
  FGridIniFileName  :=  FApplicationPath  + 'grid.ini';
  FInsertItemPath   :=  FApplicationPath  + 'InsertItem\';
  inherited;
end;

function TGlobalObject.MsgBox(const AMsg: Variant; const ATitle: string;
  const AFlag: Integer; const AHandle: HWND): integer;
//简化MessageBox函数
//返回用户的选择,与Application.MessageBox相同
var
  h     : HWND;
  Flag  : Longint;
  Title : String;
begin
  if (AFlag=0) or (AFlag=MB_OK) then
    Flag:=MB_OK + MB_ICONINFORMATION
  else
    Flag:=AFlag;
  if length(ATitle)=0 then
  begin
    if MB_ICONWARNING and AFlag=MB_ICONWARNING then
      Title:=SWarning
    else if MB_ICONQUESTION	and AFlag=MB_ICONQUESTION	then
      Title:=SConfirm
    else if MB_ICONSTOP and AFlag=MB_ICONSTOP then
      Title:=SError
    else
      Title:=SInformation;
  end else
    Title:=ATitle;
  if AHandle=0 then
    h:=Application.Handle
  else
    h:=AHandle;
  Result:=MessageBox(h,PChar(VarToStr(AMsg)),PChar(Title),Flag);
end;

initialization
  GlobalObject  :=  TGlobalObject.Create(Application);
  //Application释放就会自动释放此对象

end.

可以把所有的全局变量,函数,过程等都做为TGlobalObject的属性及方法.
引用此单元的单元通过全局对象GlobalObject访问,对工程的管理比较方便.
                                

查看回复