to hexenzhou(甲骨文) :
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值,怎么办啊?
使用设计模式的Singleton Pattern
示例如下:
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;
constructor 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;