我创建了一个窗体,需要对这个窗体类实例话,但是我想让它只能被实例化一次,当这个实例销毁后才能创建另一个实例?
解决方案 »
- delphi clientdataset 操作oracle 的blob字段
- delphi 中用sql语句整理表字段值,三个iif语句就报错
- 请问谁知道客户端不用安装ORacle就可与数据库服务器通讯?
- delphi7中stringgrid不能显示的问题?
- 怎样用dxBarManager控件动态生成菜单?
- 关于数据排序的问题!谢谢大家!
- 用InstallShield制作出的安装程序怎样安装数据库?
- 斑竹,帮我解决问题,先。控制键盘打印的问题。
- 请教如何用delphi写COM组件,哪里有这方面的例子或教材,着急~~
- 怎样在自己的程序中控制widows media player?
- 如何将二进制文件读出后转换成VARIANT类型?
- 关于FORM的简单问题(急)
procedure TForm1.Button1Click(Sender: TObject);
begin
if Form2=nil then
Form1:=TForm2.Create(Application);
Form2.Show;
end;procedure TForm2.FormClose(...);
begin
Action:=caFree;
Form2:=nil;
end;
if Form1=nil then //说明没创建。
在Form1 的OnDestroy 事件中
Form1:=nil
在Form1 的OnClose 中
Action:=caFree;关键在每次创建时判断是Form1 是否为nil
示例如下:
TMyForm = class (TForm)
protected
constructor CreateInstance;
class function AccessInstance(Request: Integer): TMyForm;
public
constructor Create;
destructor Destroy; override;
class function Instance: TMyForm;
class procedure ReleaseInstance;
end;{--------------------------------------------------------------}
implamentationconstructor TMyForm.Create;
begin
inherited Create;
raise Exception.CreateFmt('Access class %s through Instance only',
[ClassName]);
end;constructor TMyForm.CreateInstance;
begin
inherited Create;
end;destructor TMyForm.Destroy;
begin
if AccessInstance(0) = Self then AccessInstance(2);
inherited Destroy;
end;class function TMyForm.AccessInstance(Request: Integer): TMyForm;
const FInstance: TMyForm = nil;
begin
case Request of
0 : ;
1 : if not Assigned(FInstance) then FInstance := CreateInstance;
2 : FInstance := nil;
else
raise Exception.CreateFmt('Illegal request %d in AccessInstance',
[Request]);
end;
Result := FInstance;
end;class function TMyForm.Instance: TMyForm;
begin
Result := AccessInstance(1);
end;
class procedure TMyForm.ReleaseInstance;
begin
AccessInstance(0).Free;
end;这样就能保证TMyForm只有一个实例了。假设你的TMyForm有一个X的变量,你就可以这样使用它TMyForm.Instance.X := 11;在你第一次使用TMyForm的时候TMyForm的实例就被创建了。你以后每次使用TMyForm的时候都得用TMyForm.Instance的方法来返回TMyForm的实例。
要销毁TMyForm请调用TMyForm.ReleaseInstance。
class function TMyForm.AccessInstance(Request: Integer): TMyForm;
const FInstance: TMyForm = nil;
begin
case Request of
0 : ;
1 : if not Assigned(FInstance) then FInstance := CreateInstance;
2 : FInstance := nil;
else
raise Exception.CreateFmt('Illegal request %d in AccessInstance',
[Request]);
end;
Result := FInstance;
end;
这段代码不能编译,常量不能fu值,怎么办啊?
class function TMyForm.AccessInstance(Request: Integer): TMyForm;
{$J+}
const FInstance: TMyForm = nil;
{$J-}
begin
case Request of
0 : ;
MyForm.Create(Self);procedure TMyForm.FormClose(...);
begin
Action:=caFree;
end;
procedure TMyForm.FormDestroy(...);
begin
MyForm:=nil;
end;
当类实力化的时候,先检查他的值,为1表示有一个了,否则增加一次,不可以吗?