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+}狀態(tài),類型常量可以被修改,并且本質上是初始化為變量。在{$J-}狀態(tài),類型常量是真實的常量,并且任何試圖修改一個類型常量都會引起編譯器報告錯誤。可寫常量參考運行時類型常量當作變量可修改的。 在劉藝《Delphi設計模式》這本書中,也引用了這兩個例子。并分別做了闡述,這兩個例子是從網絡上找到。并做了相應的改寫。 當總是感覺Delphi使用此模式有些蹩腳,不像C++那么的舒暢。這是一個好的想法,但至少在Delphi中不是那么的實用。在delphi中,完全可以使用Initialization初始化一個變量,配合Finalization來釋放他。