标签:des blog http io ar os for sp div

{《HeadFirst设计模式》之单例模式 }
{ 编译工具: Delphi2007 for win32 }
{ E-Mail : guzh-0417@163.com }
unit uChocolateBoiler;
interface
type
TChocolateBoiler = class(TObject)
strict private
class var
FUniqueInstance: TChocolateBoiler;
strict private
FEmpty : Boolean;
FBoiled: Boolean;
constructor Create;
public
class function GetInstance: TChocolateBoiler;
function IsEmpty : Boolean;
function IsBoiled: Boolean;
procedure Fill;
procedure Drain;
procedure Boil;
end;
implementation
{ TChocolateBoiler }
procedure TChocolateBoiler.Boil;
begin
if (not IsEmpty) and (not IsBoiled) then
FBoiled := True;
end;
constructor TChocolateBoiler.Create;
begin
FEmpty := True;
FBoiled := False;
end;
procedure TChocolateBoiler.Drain;
begin
if (not IsEmpty) and IsBoiled then
FEmpty := True;
end;
procedure TChocolateBoiler.Fill;
begin
if IsEmpty then
begin
FEmpty := False;
FBoiled := False;
end;
end;
class function TChocolateBoiler.GetInstance: TChocolateBoiler;
begin
if FUniqueInstance = nil then
begin
Writeln(‘Creating unique instance of Chocolate Boiler.‘);
FUniqueInstance := TChocolateBoiler.Create;
end;
Writeln(‘Returning instance of Chocolate Boiler.‘);
Result := FUniqueInstance;
end;
function TChocolateBoiler.IsBoiled: Boolean;
begin
Result := FBoiled;
end;
function TChocolateBoiler.IsEmpty: Boolean;
begin
Result := FEmpty;
end;
end.
{《HeadFirst设计模式》之单例模式 }
{ 客户端 }
{ 编译工具: Delphi2007 for win32 }
{ E-Mail : guzh-0417@163.com }
program pChocolateBoilerController;
{$APPTYPE CONSOLE}
uses
SysUtils,
uChocolateBoiler in ‘uChocolateBoiler.pas‘;
var
aBoiler : TChocolateBoiler;
aBoiler2: TChocolateBoiler;
begin
aBoiler := TChocolateBoiler.GetInstance;
aBoiler.Fill;
aBoiler.Boil;
aBoiler.Drain;
{ will return the existing instance: aBoiler }
aBoiler2 := TChocolateBoiler.GetInstance;
FreeAndNil(aBoiler);
{ FreeAndNil(aBoiler2); 同一对象(aBoiler)不能释放两次。}
Readln;
end.
Delphi 设计模式:《HeadFirst设计模式》Delphi2007代码---单例模式之ChocolateBoiler[转]
标签:des blog http io ar os for sp div
原文地址:http://www.cnblogs.com/0x2D-0x22/p/4076337.html