A
avant
Unregistered / Unconfirmed
GUEST, unregistred user!
SINGLETON(单件)模式保证一个类仅有一个实例,并提供一个访问它的全局访问点.实现方法是:
<font color="red">让类自身负责保护它的唯一实例 </font>
做了一个试验,如下:
unit Singleton;
interface
type
TSingleton = class (TObject)
private
Prop: string;
protected
constructor Create;
public
class function GetProp: string;
class procedure SetProp(Value: string);
end;
implementation
var ASingleton: TSingleton;
constructor TSingleton.Create;
begin
if ASingleton = nil then
begin
ASingleton := inherited Create;
ASingleton.Prop := 'INIT';
end;
end;
class function TSingleton.GetProp: string;
begin
if ASingleton = nil then
TSingleton.Create;
Result := ASingleton.Prop;
end;
class procedure TSingleton.SetProp(Value: string);
begin
if ASingleton = nil then
TSingleton.Create;
ASingleton.Prop := Value;
end;
end.
经过测试,确实保证了只创建一个类的实例,我的疑惑是,我怎么释放ASingleton?什么时间释放ASingleton?
<font color="red">让类自身负责保护它的唯一实例 </font>
做了一个试验,如下:
unit Singleton;
interface
type
TSingleton = class (TObject)
private
Prop: string;
protected
constructor Create;
public
class function GetProp: string;
class procedure SetProp(Value: string);
end;
implementation
var ASingleton: TSingleton;
constructor TSingleton.Create;
begin
if ASingleton = nil then
begin
ASingleton := inherited Create;
ASingleton.Prop := 'INIT';
end;
end;
class function TSingleton.GetProp: string;
begin
if ASingleton = nil then
TSingleton.Create;
Result := ASingleton.Prop;
end;
class procedure TSingleton.SetProp(Value: string);
begin
if ASingleton = nil then
TSingleton.Create;
ASingleton.Prop := Value;
end;
end.
经过测试,确实保证了只创建一个类的实例,我的疑惑是,我怎么释放ASingleton?什么时间释放ASingleton?