示例:创建Singleton类的子类(使用环境变量)
说明:
Singleton类可以有子类,而且用这个扩展类的实例来配置一个应用是很容易的。你可以用你所需要的类的实例在运行时刻配置应用。
创建Singleton类的子类主要问题与其说是定义子类不如说是建立它的唯一实例,这样客户就可以使用它。事实上,指向单件实例的变量必须用子类的实例进行初始化。最简单的技术是在Singleton的Instance操作中决定你想使用的是哪一个单件,如用环境变量来具体实现。
代码:
unit uSingleton3;
interface
uses
SysUtils, Dialogs,IniFiles;
type
TSingleton = class
private
class var
FInstance: TSingleton;
public
constructor Create;
destructor Destroy; override;
//---
class function Instance: TSingleton;virtual;
procedure Operate;virtual;
end;
TSingletonA = class(TSingleton)
public
procedure Operate; override;
end;
TSingletonB = class(TSingleton)
public
procedure Operate; override;
end;
implementation
constructor TSingleton.Create;
begin
if FInstance = nil then
FInstance := Self
else
abort;
end;
destructor TSingleton.Destroy;
begin
FInstance := nil;
//---
inherited;
end;
class function TSingleton.Instance: TSingleton;
//---
function _GetType:string;
var
AFile: TIniFile;
begin
try
AFile := TIniFile.Create('Config.ini');
Result := AFile.ReadString('Singleton','Kind','SingletonA');
AFile.Free;
except
Result := 'SingletonA';
end;
end;
var
AType:string;
begin
if FInstance = nil then
begin
AType := _GetType;
if AType = 'SingletonA' then
FInstance := TSingletonA.Create
else if AType = 'SingletonB' then
FInstance := TSingletonB.Create
else
FInstance := TSingleton.Create;
end;
//---
Result := FInstance;
end;
procedure TSingleton.Operate;
begin
ShowMessage('Singleton');
end;
procedure TSingletonA.Operate;
begin
ShowMessage('SingletonA');
end;
procedure TSingletonB.Operate;
begin
ShowMessage('SingletonB');
end;
end.
procedure TForm1.Button5Click(Sender: TObject);
begin
TSingleton.Instance.Operate;
TSingleton.Instance.Free;
end;