raise Exception.CreateFmt('Illegal request %d in AccessInstance!', [Request]);
end;
result := FInstance;
end;
constructor TDSingleton.Create;
begin
raise Exception.CreateFmt('Access class %s only through Instance!', [ClassName]);
end;
constructor TDSingleton.CreateInstance;
begin
inherited Create;
end;
destructor TDSingleton.Destroy;
begin
if AccessInstance(0) = self then AccessInstance(2);
inherited Destroy;
end;
classfunction TDSingleton.Instance: TDSingleton;
begin
result := AccessInstance(1);
end;
classprocedure TDSingleton.ReleaseInstance;
begin
AccessInstance(0).Free;
end;
End.
这里使用了指示符{$J+} $J在Delphi中的解释是: The $J directive controls whether typed constants can be modified or not. In the {$J+} state, typed constants can be modified, and are in essence initialized variables. In the {$J-} state, typed constants are truly constant, and any attempt to modify a typed constant causes the compiler to report an error. Writeable consts refers to the use of a typed const as a variable modifiable at runtime. 【翻译】$J指示符控制常量类型是否能够被修改。在{$J+}状态,类型常量可以被修改,并且本质上是初始化为变量。在{$J-}状态,类型常量是真实的常量,并且任何试图修改一个类型常量都会引起编译器报告错误。可写常量参考运行时类型常量当作变量可修改的。 在刘艺《Delphi设计模式》这本书中,也引用了这两个例子。并分别做了阐述,这两个例子是从网络上找到。并做了相应的改写。 当总是感觉Delphi使用此模式有些蹩脚,不像C++那么的舒畅。这是一个好的想法,但至少在Delphi中不是那么的实用。在delphi中,完全可以使用Initialization初始化一个变量,配合Finalization来释放他。